Reputation: 299
I have a problem on my codes that uses jquery ajax to execute the php script and returns the data back to the browser. I want to return more one value from the 'echo' output of my php script. So I use json_encode to return the data inform of arrays. But my codes here does not return any value and no responses happening in my browser. Here is my codes.
// AJAX Code To Submit Form
// Get the value from selectbox
var so = $(this).find('option:selected').text();
var dataString = 'so1='+ so;
$.ajax({
type: "POST",
url: "functions/ajaxsubmit.php",
data: dataString,
cache: false,
success: function(response){
var pos1_text = $("#pos1").text(response.a);
}
});
and heres my php code ajaxsubmit.php
<?php
include("connection.php");
//Fetching Values from URL
$sign1 = $_POST['so1'];
//Display Signing Position
$sql = "SELECT * FROM signing_officer WHERE signing_incharge = '$sign1'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
$dbSigning_id = $row['signing_id'];
$dbSigning_position = $row['signing_position'];
}
$output = array('a' => $dbSigning_id, 'b' => $dbSigning_position);
echo json_encode($output, JSON_FORCE_OBJECT);
?>
Can anyone help me find the bug with this code? Really needed this.. Thankyou
Upvotes: 0
Views: 2661
Reputation: 416
While I agree with @Aram Tchekrekjian comment, I think the mistake is on jQuery because your AJAX request is not made accordingly to receive JSON data
Two ways of achieving so are (using ajax function):
$.ajax({
type: "POST",
url: "functions/ajaxsubmit.php",
data: dataString,
cache: false,
success: function(response){
var pos1_text = $("#pos1").text(response.a);
},
dataType: 'json'
});
Or (by using post function):
$.post("functions/ajaxsubmit.php", dataString, function(response){
var pos1_text = $("#pos1").text(response.a);
}, 'json');
Voila !
Additionally, I am targeting @Aram Tchekrekjian answer because I feel it completes mine:
$dbSigning_ids = array();
$dbSigning_positions = array();
while($row = mysql_fetch_array($result)) {
$dbSigning_ids[] = $row['signing_id'];
$dbSigning_positions[] = $row['signing_position'];
}
$dbSigning_array = array($dbSigning_ids,$dbSigning_positions);
echo json_encode($dbSigning_array);
Latter seems to solve your issue, but I also see mistakes in the jQuery implementation.
Cheers,
Upvotes: 1
Reputation: 935
You are only returning the last elements in your fetched array, you need to define arrays for your fields, and then put them into another container array then echo it through json_encode:
$dbSigning_ids = array();
$dbSigning_positions = array();
while($row = mysql_fetch_array($result)) {
$dbSigning_ids[] = $row['signing_id'];
$dbSigning_positions[] = $row['signing_position'];
}
$dbSigning_array = array($dbSigning_ids,$dbSigning_positions);
echo json_encode($dbSigning_array);
Also, Brandon's comment is quite important, that you need to inspect the network from browser dev tools and see if you are getting the json response.
Upvotes: 0