March 18, 2013

jQuery Ajax Appears to be POSTing but can't catch the values

Question by MG55114

What am I missing here?

I am trying to pass an array of strings via a jQuery AJAX POST.

var json = JSON.stringify( selectedTags );
var data = json;

var apiCall = $.ajax({
    url: "service-getemails-multiple.php",
    data: data,
    type: "POST"
    //beforeSend: alert(data)
}).done(function(data) {
    $(".ui-dialog-titlebar-close").show();
    var html = '<textarea style="width: 100%; height: 90%" id="emailsTextbox">' + data + '</textarea>';
    html += data;
    html += "" target="new">Send Email</a></p>";
    $("#dialog").html(html);
    $("#emailsTextbox").focus();
    $("#emailsTextbox").select();
});

My catcher (“service-getemails-multiple.php”) is currently extremely simple and I don’t understand why it’s failing to catch the AJAX request (POST).

<?php

var_dump($_POST);

?>

In Firebug, I can see the values being passed under XHR/Post as parameters and under source. If I uncomment “beforeSend: alert(data)” that alerts the values just fine.

So what am I doing wrong?

Answer by ITroubs

try this:

var json = JSON.stringify( selectedTags );
var thedata = json;
....
var apiCall = $.ajax({
    url: "service-getemails-multiple.php",
    data: {mydata: thedata},
    type: "POST"
    //beforeSend: alert(data)
}).done(function(data) {
    $(".ui-dialog-titlebar-close").show();
    var html = '<textarea style="width: 100%; height: 90%" id="emailsTextbox">' + data + '</textarea>';
    html += data;
    html += "" target="new">Send Email</a></p>";
    $("#dialog").html(html);
    $("#emailsTextbox").focus();
    $("#emailsTextbox").select();
});

Answer by Starx

I think the function is confused about data: data part.

Try this

var apiCall = $.ajax({
    url: "service-getemails-multiple.php",
    data: json, // <!-- Use json instead. Its the same thing
    type: "POST"
    //beforeSend: alert(data)
}).done(function(data) {
    $(".ui-dialog-titlebar-close").show();
    var html = '<textarea style="width: 100%; height: 90%" id="emailsTextbox">' + data + '</textarea>';
    html += data;
    html += "" target="new">Send Email</a></p>";
    $("#dialog").html(html);
    $("#emailsTextbox").focus();
    $("#emailsTextbox").select();
});

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!