Suraya Suraya - 18 days ago 6
Ajax Question

jQuery Ajax not sending Post data to PHP file

I'm trying to send variables from my JavaScript to a PHP file using AJAX but it's not working. I've looked through all the similar asked questions (there are a bunch) but have yet to find a solution.

This is my first php file (one with the form, sends data to JavaScript):

<option value="imageOne" data-cuteform-image='assets/SketchThumbnails/imageOne.png></option>
<input id="inputURLID" type="text" name="inputURL">

<button type="submit" onclick="handleInputs(document.getElementById('sketch').value, document.getElementById('inputURLID').value); return false;">Submit</button>


JavaScript (where AJAX call is):

var content = {
'sketch': pickedSketch,
'songUrl': enteredURL
};
$.ajax({
type: "POST",
url: "loadSketch.php",
data: content,
success: function (data, text) {
// alert("success");
// console.log(data);
// console.log(text);

window.location.href = "loadSketch.php";

},
error: function (request, status, error) {
alert(request.responseText);
}
});


PHP (loadSketch.php):

if(isset($_POST['songUrl']))
{
$temp = $_POST['songUrl'];
echo $temp;
echo "received AJAX data";
} else {
echo "nothing in post variable";
}


When I get redirected to loadSketch.php (from the successful ajax call), "nothing in post variable" gets echoed out. Any ideas what I'm doing wrong?

Any insight is much appreciated! :)

Answer

Nothing is in songURL because when your Ajax function returns it is redirecting to the same page you just posted to. It is creating a new HTTP request to that PHP file with no data sending to it. Remove the comments on the console messages and you'll see the correct echo messages.

$.ajax({
type: "POST",
url: "loadSketch.php",
data: content,
success: function (data, text) {
    alert("success");
    console.log(data);

},
error: function (request, status, error) {
    alert(request.responseText);
}
});