So I'm trying to make the simplest of communications between AJAX and PHP, and send a single variable to my PHP, where it will be stored, but nothing seems to work u_u
This here is my AJAX code
$(document).ready(function() {
$("#ch1").click(function(){
document.getElementById('stf').style.visibility="visible";
document.getElementById('ch2').style.visibility="visible";
document.getElementById('reto1').src="slides/reto1_completo.png";
var counter = 1;
var longform = $("input:text").serialize();
$.ajax({
type: GET,
url: 'counter.php',
data: longform + "counter=<?php echo $counter; ?>",
})
})
})
And this one here is my PHP
session_start();
$db = mysql_connect("localhost","db","pass");
if(!$db) die("Error");
mysql_select_db("db",$db);
$counter = $_GET['counter'];
$insert = mysql_query("UPDATE usuarios SET retos='$counter' WHERE email = '$correo'") or die(mysql_error());
So this is it, I'm sure it's the simplest of mistakes, but I just can't figure it out. Thanks in advance
You're building your data string wrong. longform
will look something like:
foo=bar&baz=qux
which you then tack on the coutner value directly:
foo=bar&baz=quxcounter=$counter
You need a &
separator:
data: longform + "&counter=<?php echo $counter; ?>",
^---here
so counter
will be its own key, not part of the baz
value that's at the end of longform
.
What about this?
$.get("url.php?"+longform+"&counter=1");
Edit: Or
longform.counter = 1;
$.get("url.php",longform);
<?php echo $counter; ?>
doesn't write anything because the counter insn't defined inside that php code, so you must replace that by another method for finding count (or use for instance SET retos=retos+1
in the mysql, it you want that).Selecting some parts of your code and correcting it I achieved this, to which I suggest you take a look, because it runs well (and then you add the other parts):
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#ch1").click(function(){
alert("hey!");
$.ajax({
type: "GET",
url: './counter.php',
data: "counter=<?php echo '...'; ?>",
success: function(data, text_status, jqXHR){
alert(data);
},
error: function(XML_http_request, text_status, error_thrown){
alert(error_thrown);
}
})
});
})
</script>
</head>
<body>
<div id="ch1">hello world!</div>
</body>
</html>
in the other php file:
<?php
# connect to the database...
# OK...
$counter = $_GET['counter'];
# change database's info...
# OK...
echo $counter; #for debug purposes, to verify that in this code the php is receiving the string passed by the html.
?>