Sending back multiple results from PHP via AJAX - php

i have setup some ajax, which i am just testing now, pretty much the idea behind it is to send some data from dropdown boxes to a php script, do some calculations and then return the result, it does it well and returns the result, but now rather than just sending back one result and outputting that, i want to send back multiple results and output them, i am able to send multiple data to the php script, so i am sure i can send multiple back.
Anyway it only sends the first result back and not the rest.
Here is the AJAX
<script>
$("document").ready(function (){
$(".add_extension").change(function(){
var m = document.getElementById('meter_square');
var meter_square = m.options[m.selectedIndex].value;
var s = document.getElementById('story_height');
var story_height = s.options[s.selectedIndex].value;
$.ajax({
type: "GET",
url: "script.php",
data: { meter_square: meter_square, story_height: story_height },
dataType: "json",
statusCode: {
200: function (result, result2)
{
$("#expected_gain").html(result.value);
$("#house_price").html(result2.value2);
}
}
});
})
});
</script>
And here is the php script
<?php
$meter_square = $_GET["meter_square"];
$story_height = $_GET["story_height"];
$result = $meter_square + $story_height;
$result2 = $meter_square * $story_height;
echo json_encode(array("value" => $result, "value2" => $result2));
?>
You can see that i have already tried to give it a go from what i thought might work, if you need any other code or want me to remove the code i added which doesn't work, then let me know.
Thanks for all and any help

You're only going to receive one response object:
function (response) {
$("#expected_gain").html(response.value);
$("#house_price").html(response.value2);
}

Try this. Think it will help. No need to use status codes if u gonna use only success case
$.ajax({
type: "GET",
url: "script.php",
data: { meter_square: meter_square, story_height: story_height },
dataType: "json",
success: function(data){
$("#expected_gain").html(data.value);
$("#house_price").html(data.value2);
}
});

Related

jQuery Ajax(post), data not being received by PHP

The Ajax function below sends data from a page to the same page where it is interpreted by PHP.
Using Firebug we can see that the data is sent, however it is not received by the PHP page. If we change it to a $.get function and $_GET the data in PHP then it works.
Why does it not work with $.post and $_POST
$.ajax({
type: "POST",
url: 'http://www.example.com/page-in-question',
data: obj,
success: function(data){ alert(data)},
dataType: 'json'
});
if there is a problem, it probably in your php page.
Try to browse the php page directly in the browser and check what is your output.
If you need some inputs from post just change it to the GET in order to debug
try this
var sname = $("#sname").val();
var lname = $("#lname").val();
var html = $.ajax({
type: "POST",
url: "ajax.class.php",
data: "sname=" + sname +"&lname="+ lname ,
async: false
}).responseText;
if(html)
{
alert(html);
return false;
}
else
{
alert(html);
return true;
}
alax.class.php
<php
echo $_REQUEST['sname'];
echo $_REQUEST['sname'];
?>
Ajax on same page will not work to show data via POST etc because, PHP has already run that's why you would typically use the external page to process your data and then use ajax to grab the response.
example
success: function(){
$('#responseDiv').text(data);
}
You are posting the data... Check if the target is returning some data or not.
if it returns some data then only you can see the data otherwise not.
add both success and error.. so that you can get what exactly
success: function( data,textStatus,jqXHR ){
console.log(data);//if it returns any data
console.log(textStatus);//or alert(textStatus);
}
error: function( jqXHR,textStatus,errorThrown ){
console.log("There is some error");
console.log(errorThrown);
}

how do I get my ajax data into a php array?

I have the following data in a JS script:
$("#holdSave").live('click', function () {
var arr = {};
var cnt = 0;
$('#holdTable tbody tr').each(function () {
arr[cnt] = {
buyer: $(this).find('#tableBuyer').html(),
sku: $(this).find('#tableSku').html(),
isbn: $(this).find('#tableISBN').html(),
cost: $(this).find('#tableCost').val(),
csmt: $(this).find('#tableConsignment').val(),
hold: $(this).find('#tableHold').val()
};
cnt++;
}); //end of holdtable tbody function
console.log(arr);
$.ajax({
type: "POST",
url: "holdSave.php",
dataType: "json",
data: {
data: arr
},
success: function (data) {
} // end of success function
}); // end of ajax call
}); // end of holdSave event
I need to send this to a php file for updating the db and emailing that the update was done. My console.log(arr); shows the objects when I run it in firebug, but I can't get any of the information on the php side. Here is what I have for php code:
$data = $_POST['data'];
print_r($data); die;
At this point I am just trying to verify that there is info being sent over. My print_r($data); returns nothing.
Can anyone point me in the right direction please?
dataType: "json" means you are expecting to retrieve json data in your request not what you are sending.
If you want to send a json string to be retrieved by $_POST['data'] use
data: {data: JSON.stringify(arr)},
Use the json_encode() and json_decode() methods
Use the next way:
data = {key1: 'value1', key2: 'value2'};
$.post('holdSave.php', data, function(response) {
alert(response);
});
Note: haven't tested it, make sure to look for parse errors.

Retrieve JSON Data with AJAX

Im trying to retrieve some data from JSON object which holds location information such as streetname, postcode etc. But nothing is being retrieved when i try and put it in my div. Can anybody see where im going wrong with this?
This is my ajax code to request and retrieve the data
var criterion = document.getElementById("address").value;
$.ajax({
url: 'process.php',
type: 'GET',
data: 'address='+ criterion,
success: function(data)
{
$('#txtHint').html(data);
$.each(data, function(i,value)
{
var str = "Postcode: ";
str += value.postcode;
$('#txtHint').html(str);
});
//alert("Postcode: " + data.postcode);
},
error: function(e)
{
//called when there is an error
console.log(e.message);
alert("error");
}
});
When this is run in the broswer is just says "Postcode: undefined".
This is the php code to select the data from the database.
$sql="SELECT * FROM carparktest WHERE postcode LIKE '".$search."%'";
$result = mysql_query($sql);
while($r = mysql_fetch_assoc($result)) $rows[] = $r;
echo json_encode($rows), "\n"; //Puts each row onto a new line in the json data
You are missing the data type:
$.ajax({
dataType: 'json'
})
You can use also the $.getJSON
EDIT: example of JSON
$.getJSON('process.php', { address: criterion } function(data) {
//do what you need with the data
alert(data);
}).error(function() { alert("error"); });
Just look at what your code is doing.
First, put the data directly into the #txtHint box.
Then, for each data element, create the string "Postcode: "+value.postcode (without even checking if value.postcode exists - it probably doesn't) and overwrite the html in #txtHint with it.
End result: the script is doing exactly what you told it to do.
Remove that loop thing, and see what you get.
Does your JSON data represent multiple rows containing the same object structure? Please alert the data object in your success function and post it so we can help you debug it.
Use the
dataType: 'json'
param in your ajax call
or use $.getJSON() Which will automatically convert JSON data into a JS object.
You can also convert the JSON response into JS object yourself using $.parseJSON() inside success callback like this
data = $.parseJSON(data);
This works for me on your site:
function showCarPark(){
var criterion = $('#address').val();
// Assuming this does something, it's yours ;)
codeAddress(criterion);
$.ajax({
url: 'process.php',
type: 'GET',
dataType: 'json',
data: {
address: criterion
},
success: function(data)
{
$("#txtHint").html("");
$.each(data, function(k,v)
{
$("#txtHint").append("Postcode: " + v.postcode + "<br/>");
});
},
error: function(e)
{
alert(e.message);
}
});
}

What is wrong with my AJAX jQuery function?

I have a function that does a simple call to a PHP file with a simple INSERT statement in it. When I click the corresponding button, the function does not even send the AJAX request or return false.
$(function() {
$('#add_employee_submit').click(function() {
var fname = $('#eie_fname').text();
var lname = $('#eie_lname').text();
var doNo = $('#eie_doNo').val();
var emergency = 0;
if($('#eie_emergency').is(':checked')) {
emergency = 1;
}
$.ajax({
type: "POST",
url: "scripts/employee_information_entry.php",
data: "fname="+fname+"&lname="+lname+"&dono="+doNo+"&emergency="+emergency,
success: function() {
showMessage('employee_added');
}
});
return false;
});
});
Am I missing something obvious here?
EDIT:
Instead of wasting more time trying to figure out what was wrong I went with #ThiefMaster's advice and used jquery.malsup.com/form. This is working correctly and is a lot let work.
Thanks for everyone's help. :)
The success function should have a response parameter i.e. your code would be like:
$.ajax({
type: "POST",
url: "scripts/employee_information_entry.php",
data: "fname="+fname+"&lname="+lname+"&dono="+doNo+"&emergency="+emergency,
success: function(response) {
showMessage('employee_added');
}
});
Also check if the various id's are present there or not.
The best method to check is to use firebug/developer console to check what parameters are being sent and what are being received.

Jquery, reading JSON variables received from PHP

Sorry if this is basic, but I have been dealing with figuring this out all day and have gotten to where I can do everything I need with Jquery and cakephp (not sure if cakephp matters in this or if its same as any PHP), I want to return a variable from a cakephp function to jquery, I had read about how to do it, like here:
the cakephp:
$test[ 'mytest'] = $test;
echo json_encode($test);
and the jquery:
$.ajax({
type: 'POST',
url: 'http://localhost/site1/utilities/ajax_component_call_handler',
data: {
component_function: component_function,
param_array: param_array
},
dataType: "json",
success: function(data) {
// how do i get back the JSON variables?
}
});
I just can't figure out how to get one or more variables back into usable form within jquery, I just want the variable so I can do whatever else with it, I've been looking at what I can find through searching but its not making it fully clear to me.. thanks for any advice.
The JSON variables are in the data variable. In your case, it'll look like this:
var data = {
myTest: "Whatever you wrote here"
};
... so you can read it from data.myTest.
(Not sure whether it's relevant but you can remove the http://localhost/ part from the URL;
AJAX does not allow cross-domain requests anyway.)
Your variables are in data.
$.ajax({
type: 'POST',
url: 'http://localhost/site1/utilities/ajax_component_call_handler',
data: {
component_function: component_function,
param_array: param_array
},
dataType: "json",
success: function(data) {
// how do i get back the JSON variables?
var values = eval( data ); //if you 100 % trust to your sources.
}
});
Basically data variable contain the json string. To parse it and convert it again to JSON, you have to do following:
$.ajax({
type: 'POST',
url: 'http://localhost/site1/utilities/ajax_component_call_handler',
data: {
component_function: component_function,
param_array: param_array
},
dataType: "json",
success: function(data) {
json = $.parseJSON(data);
alert(json.mytest);
}
I haven't test it but it should work this way.
Note that when you specify dataType "json" or use $.getJSON (instead of $.ajax) jQuery will apply $.parseJSON automatically.
So in the "success" callback you do not need to parse the response using parseJSON again:
success: function(data) {
alert(data.mytest);
}
In case of returning a JSON variable back to view files you can use javascript helper:
in your utilities controller:
function ajax_component_call_handler() {
$this->layout = 'ajax';
if( $this->RequestHandler->isAjax()) {
$foobar = array('Foo' => array('Bar'));
$this->set('data', $foobar);
}
}
and in your view/utilities/ajax_component_call_handler.ctp you can use:
if( isset($data) ) {
$javascript->object($data); //converts PHP var to JSON
}
So, when you reach the stage in your function:
success: function(data) {
console.log(data); //it will be a JSON object.
}
In this case you will variable type handling separated from controllers and view logic (what if you'll need something else then JSON)...

Categories