Reputation: 3411
I've used ajax quite a bit to send data off to a php page and get something back, but I'm not sure how to determine what specifically gets sent back. I understand what most of the fields here do, but I have a few questions as well.
My current code looks like this:
$.ajax({
url: "search.php",
type: "post",
dataType: "json",
data: {partNumber: q , newType:newType},
success: function(data) {
console.log(data);
}
});
One thing I don't fully understand is how the success:
line works. When I say success: function(data)
, it's my understanding that I'm saying "upon success (of something? I'm not sure what), the information that is returned to this ajax function will be called data
," and then inside the brackets, I'm choosing to console.log
that data
.
Please correct me if I'm wrong in that assumption.
Ultimately, my php page will do a ton of work and return an array with data in it. If the last line of my php code is:
$myArray = array("bob","dan","carl","mike");
how do I choose for that to be returned to ajax? The php page is working fine, but right now my console.log(data)
line of code is not returning anything.
Upvotes: 1
Views: 168
Reputation: 6652
1) Your on "success" is basically saying when there is not an error that occurs.
Here is testing error
$.ajax({
url: 'search.php',
success: function(){
alert('success');
},
error: function(){
alert('failure');
}
});
2) For your "data" what you echo on the php side gets returned into the variable defined in your
function(results) {
for example if you want to return an array you may want to return "echo" json
your array should include a key and a value
$myArray = array("key" => "value");
echo json_encode($myArray);
and on the jquery side parse the json object returned.
function(data) {
var obj = jQuery.parseJSON(data);
alert(obj.key);
3) Pass JSON Objects
var JSONObject= {"partNumber":q, "newType":newType};
var jsonData = JSON.parse( JSONObject );
var request = $.ajax({
url: "search.php",
type: "POST",
data: jsonData,
dataType: "json"
});
Upvotes: 1
Reputation: 8659
You are not supposed to return
anything from the php page called by your ajax, you're supposed to echo
it (i.e. write it to the response).
echo json_encode($myArray);
And if what you're echoing is not JSon, then take out dataType: "json"
. The success
function means that the request was successful, i.e. a response was received back from the server with status 200. There is also an error
method you can use for when you don't get a successful response back.
success: function(data) {
console.log(data);
},
error: function(data) {
console.log("Error: "+data);
}
Upvotes: 4