0

I'm trying to send data using AJAX to a PHP page (which queries a database) and return specific values. I then will display the results.

I've found several examples on how to pass data using AJAX. This is not my problem. It's how to get the multiple results from a SQL query back to the original page.

page2.php

$prod01 = $_REQUEST['prod01'];
$prod02 = $_REQUEST['prod02'];

$cost01 = mysqli_fetch_array(mysqli_query($db,"SELECT `cost`,`cost2` FROM `info` WHERE `blah`='".$prod01."'"));
$cost02 = mysqli_fetch_array(mysqli_query($db,"SELECT `cost`,`cost2` FROM `info` WHERE `blah`='".$prod02."'"));

$getcost01 = $qty01 * $cost01[0];
$getcost02 = $qty02 * $cost02[0];

$foo = array('result01' => $getcost01, 'result02' => $getcost02);
echo json_encode($foo);

page1.php

var prod01 = $("#prod01").val();
var prod02 = $("#prod02").val();


$.ajax({  
type: "POST",  
url: "page2.php",
dataType: 'json',  
data : { prod01 : 'pro01', prod02 : 'prod02'},
cache: false,
success: function(result){
  $('.showit01').text(result.result01);
  $('.showit02').text(result.result02);
}
});

The result of the above is:

$getcost01
$getcost02

Not the expected SQL result from database.

When I navigate to "/page2.php?prod01=ABC&prod02=DEF" it displays as expected:

{"result01":"100","result2":"200"}
11
  • 1
    Also, that sucks: stackoverflow.com/questions/60174/… Nov 8, 2016 at 19:43
  • 1
    Sorry, your life is going to suck if you query the database like that. Check the link. Nov 8, 2016 at 20:08
  • 1
    I don't see how you can possibly get that JSON result. $getcost01 is an array, not a single value. The PHP script needs to use $getcost01['thing1'] to get a number.
    – Barmar
    Nov 8, 2016 at 20:08
  • 1
    There's no way the script could be returning the variable names, that would only happen if you quoted the variable in the array assignment, just like in the original version of your previous question.
    – Barmar
    Nov 8, 2016 at 20:09
  • 3
    You're obviously editing your script before posting it here, to change variable names. But when you do that, it looks like you're editing away the problem. Post the real code without any editing, and we might be able to figure out what's really wrong.
    – Barmar
    Nov 8, 2016 at 20:10

1 Answer 1

0

Seems there was an issue with the ajax. I changed

data : { prod01 : 'pro01', prod02 : 'prod02'},

to

var dataString = 'prod01='+ prod01 +'&prod02='+ prod02;

$.ajax({  
type: "POST",  
url: "page2.php?",
dataType: 'json',  
data : dataString ,
cache: false,
success: function(result){
  $('.showit01').text(result.result01);
  $('.showit02').text(result.result02);
  }
});

I'm assuming my ajax was not formatted properly? I can't explain it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.