cannot display array values in ajax success function - php

$.ajax({
type: "GET",
url: 'http://localhost/abc/all-data.php',
data: {
data1: "1"},
success: function(response)
{
alert(response);
}
});
return false;
I want to display each element of array one by one in success function of the ajax currently i get all elements to gether
this is my php code
$i=0;
while($row = mysqli_fetch_assoc( $qry )){
$temp[$i]['c_n'] = $row['c_name'];
$temp[$i]['j_t'] = $row['Job_Title'];
$temp[$i]['des'] = $row['description'];
$temp[$i]['req'] = $row['requirments'];
$temp[$i]['dat'] = $row['posted'];
$i++;
}
$data = array('temp'=> $temp);
echo JSON_encode($temp);
I do appreciate your helps

you probably use something like this in your success function :
response.temp.forEach(function(element){
console.log(element.c_n) ;
console.log(element.j_t) ;
console.log(element.des) ;
console.log(element.req) ;
console.log(element.dat) ;
});

In your success function, you need to json parse your response
var data = JSON.parse(response);
You can access to your data:
data['temp']
If you want your response parsed to json automaticallym you can setup your ajax settings like this:
$.ajaxSetup ({
contentType: "application/json",
dataType: 'json'
});
Then you don't need to call JSON.parse anymore.

Your code:
$i=0; while($row = mysqli_fetch_assoc($qry)){
$temp[$i]['c_n'] = $row['c_name'];
$temp[$i]['j_t'] = $row['Job_Title'];
$temp[$i]['des'] = $row['description'];
$temp[$i]['req'] = $row['requirments'];
$temp[$i]['dat'] = $row['posted'];
$i++;
} $data = array('temp'=> $temp); echo JSON_encode($temp);
Please change the last line as
return JSON_encode($data);
Hope this helps you :)

Related

Expect json array in AJAX

How is it possible for me to get my Ajax to expect my array within my success. Currently I presume I use a flat object and this needs to grab all the data passed back to the client side so I can update my notifications.
I presume everything else is correct!
{"num":1,"670":{"notification_id":"670","notification_content":"
Lucy Botham posted a status on your
wall","notification_throughurl":"singlepoststreamitem.php?
streamitem_id=545","notification_triggeredby"
"85","notification_status":"1"},"671":
{"notification_id":"671","notification_content":"Lucy Botham
posted a status on your
wall","notification_throughurl":"singlepoststreamitem.php?streamitem_id=546"
,"notification_triggeredby":"85","notification_status":"1"}}
SERVER SIDE
while($row = mysqli_fetch_assoc($com)){
$id = $row['notification_id'];
$num = mysqli_num_rows($com);
if($num){
$json['num'] = 1;
}else{
$json['num'] = 0;
}
$json[$id]['notification_id'] = $row['notification_id'];
$json[$id]['notification_content'] = $row['notification_content'];
$json[$id]['notification_throughurl'] = $row['notification_throughurl'];
$json[$id]['notification_triggeredby'] = $row['notification_triggeredby'];
$json[$id]['notification_status'] = $row['notification_status'];
}
echo json_encode($json);
CLIENT
function loadIt() {
$.ajax({
type: "GET",
url: "viewajax.php?
notification_id="+notification_id+"
&notification_targetuser="+notification_targetuser+
"&notification_triggeredby="+notification_triggeredby,
dataType:"json",
success: function(data){
//do something
)
use json.parse()
success: function(data){
var a = JSON.parse(data);
//loop var a to get your data
}
See this link, you might get some idea.

set json data array in function response

Here is my ajax function in response I am getting result but I don't know how to set that response in my page. Is it possible with json_decode or I have to try something else
JSON file is
<?php
$group_id = $_POST['group_id'];
$query = "SELECT *,group_id FROM contact JOIN addressgroup ON addressgroup.contact_id = contact.contact_id WHERE group_id IN (".$group_id.") GROUP BY contact.contact_id";
$res = mysql_query($query);
$data = array();
$k=0;
while($row = mysql_fetch_array($res))
{
$data[$k][0] = $row['user_id'];
$data[$k][1] = $row['first_name'];
$data[$k][2] = $row['middle_name'];
$data[$k][3] = $row['last_name'];
$k++;
}
echo json_encode(array($data));
?>
AJAX function
var myarray;
function getcon() {
myarray = [];
myarray.push($(".group_id").val());
$.ajax({
dataType: "json",
type: "POST",
url: "getcon.php",
data: 'group_id=' + myarray.join(),
success: function(data) {
totalRecords=data.length;
zone.fnClearTable();
for(var i=0; i < (data.length); i++) {
zone.fnAddData([
data[k][0],
data[k][1],
data[k][2],
data[k][3],
]);
}
return false;
}
});
return false;
}
As your Response is an JSON object..
you have to use it like this:-
replace
echo json_encode(array($data));
by
echo json_encode($data); /* because $data is already an array*/
and keep it same as it was earlier
while($row = mysql_fetch_array($res))
{
$data[] = $row['user_id'];
$data[] = $row['first_name'];
$data[] = $row['middle_name'];
$data[] = $row['last_name'];
$k++;
}
<script>
var myarray;
function getcon() {
myarray = [];
myarray.push($(".group_id").val());
$.ajax({
dataType: "json",
type: "POST",
url: "getcon.php",
data: 'group_id=' + myarray.join(),
success: function(data) {
console.log(data)/* check the structure of data here*/
zone.fnClearTable();
zone.fnAddData([
data.user_id.,
data.first_name,
data.middle_name,
data.last_name,
]);
return false;
}
});
return false;
}
</script>
JSON is an object! Your are getting object, so in your ajax function You must use some loop function like for or $.each JQuery functions.
`success : function (data) {
$.each (data,function(key,val){
$("#someId).html(key + " - " + val)
}
}`

How to pass mysql result as jSON via ajax

I'm not sure how to pass the result of mysql query into html page via ajax JSON.
ajax2.php
$statement = $pdo - > prepare("SELECT * FROM posts WHERE subid IN (:key2) AND Poscode=:postcode2");
$statement - > execute(array(':key2' => $key2, ':postcode2' => $postcode));
// $row = $statement->fetchAll(PDO::FETCH_ASSOC);
while ($row = $statement - > fetch()) {
echo $row['Name']; //How to show this in the html page?
echo $row['PostUUID']; //How to show this in the html page?
$row2[] = $row;
}
echo json_encode($row2);
How to pass the above query result to display in the html page via ajax below?
my ajax
$("form").on("submit", function () {
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "ajax2.php", //Relative or absolute path to response.php file
data: data,
success: function (data) {
//how to retrieve the php mysql result here?
console.log(data); // this shows nothing in console,I wonder why?
}
});
return false;
});
Your json encoding should be like that :
$json = array();
while( $row = $statement->fetch()) {
array_push($json, array($row['Name'], $row['PostUUID']));
}
header('Content-Type: application/json');
echo json_encode($json);
And in your javascript part, you don't have to do anything to get back your data, it is stored in data var from success function.
You can just display it and do whatever you want on your webpage with it
header('Content-Type: application/json');
$row2 = array();
$result = array();
$statement = $pdo->prepare("SELECT * FROM posts WHERE subid IN (:key2) AND Poscode=:postcode2");
$statement->execute(array(':key2' => $key2,':postcode2'=>$postcode));
// $row = $statement->fetchAll(PDO::FETCH_ASSOC);
while( $row = $statement->fetch())
{
echo $row['Name'];//How to show this in the html page?
echo $row['PostUUID'];//How to show this in the html page?
$row2[]=$row;
}
if(!empty($row2)){
$result['type'] = "success";
$result['data'] = $row2;
}else{
$result['type'] = "error";
$result['data'] = "No result found";
}
echo json_encode($row2);
and in your script:
$("form").on("submit",function() {
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "ajax2.php", //Relative or absolute path to response.php file
data: data,
success: function(data) {
console.log(data);
if(data.type == "success"){
for(var i=0;i<data.data.length;i++){
//// and here you can get your values //
var db_data = data.data[i];
console.log("name -- >" +db_data.Name );
console.log("name -- >" +db_data.PostUUID);
}
}
if(data.type == "error"){
alert(data.data);
}
}
});
return false;
});
In ajax success function you can use JSON.parse (data) to display JSON data.
Here is an example :
Parse JSON in JavaScript?
you can save json encoded string into array and then pass it's value to javascript.
Refer below code.
<?php
// your PHP code
$jsonData = json_encode($row2); ?>
Your JavaScript code
var data = '<?php echo $jsonData; ?>';
Now data variable has all JSON data, now you can move ahead with your code, just remove below line
data = $(this).serialize() + "&" + $.param(data);
it's not needed as data variable is string.
And in your ajax2.php file you can get this through
json_decode($_REQUEST['data'])
I would just..
$rows = $statement->fetchAll(FETCH_ASSOC);
header("content-type: application/json");
echo json_encode($rows);
then at javascript side:
xhr.addEventListener("readystatechange",function(ev){
//...
var data=JSON.parse(xhr.responseText);
var span=null;
var i=0;
for(;i<data.length;++i){span=document.createElement("span");span.textContent=data[i]["name"];div.appendChild(span);/*...*/}
}
(Don't rely on web browsers parsing it for you in .response because of the application/json header, it differs between browsers... do it manually with responseText);

Ajax call keeps returning null

My js:
$('#select').change(function() {
var name = $(this).val();
$.ajax({
type: "POST",
url: "data/grab.php",
data: { type: "hops", name: name },
dataType: "json",
success: function(data) {
alert(data);
var aa = data['aa'];
$('#hops-aa').val(aa);
}
});
});
grab.php
<?php
$type = $_POST['type'];
$name = $_POST['name'];
if ($type == 'hops') {
$result = $name;
}
$result = json_encode($result);
return $result;
I added the alert() in the ajax call to double check what I'm getting back from the script, and it's always null. Anything I'm missing?
You need to actually echo or print the $result. In PHP using return from the file scope does not send the returned value to the output stream.
You use echo to print out the results in PHP, not return:
echo $result;
(As previous answers stated)
You need to echo/print the $result variable.
<?php
$type = $_POST['type'];
$name = $_POST['name'];
if ($type == 'hops') {
$result = $name;
}
$result = json_encode($result);
echo $result; // return $result;
?>

PHP Arrays - jQuery referencing issue

I have the following php:
1) echo json_encode(array('message' => 'Invalid Login Details: '.$user));
I also have the following:
2) $row = mysql_fetch_assoc($result);
echo(json_encode($row));
Now consider the following jQuery:
$.ajax({
type: "POST",
url: "get_login.php",
data: {username: getusername, password:getpassword, usertype:getusertype},
dataType: "json",
success: function(data) {
$("#message_ajax").html("<div class='successMessage'>" + data.message +"</div>");
}
})
This succeeds for (1) but not for (2). This is obviously because jQuery expects a php response containing a message variable. (2) does not conform to this...I don;t know how to make this work as I am using different methods for creating the arrays...
How can I make $row in the php compatible with the data.message in the jQuery?
try:
$data = array();
$data["message"] = "Valid request";
$data["row"] = mysql_fetch_assoc($result);
echo(json_encode($data));
message = row:
$data = array();
$data["message"] = mysql_fetch_assoc($result);
echo(json_encode($data));
or two line solution (inspired by val):
$row = mysql_fetch_assoc($result);
echo(json_encode(array("message" => $row)));
Try
$row = mysql_fetch_assoc($result);
echo(json_encode(array('message'=>'I am the message','result'=>$row));
Then to answer your second question on the comments something similar to this could show the information ....
$.ajax({
type: "POST",
url: "get_login.php",
data: {username: getusername, password:getpassword, usertype:getusertype},
dataType: "json",
success: function(data) {
$("#message_ajax").html("<div class='successMessage'>" + data.message +"</div>");
var html = '';
for(var i = 0; i<data.result.length;i++){
html +='<div>'+data.result[i].fname+'</div>';
}
$('#result').html(html);
}
})
ofcourse you need to edit it abit where applicable .
i believe you don't have $row['message'] from mysql_fetch_assoc.
you have to explicitely define the message key on the array before json_encode.
$row = mysql_fetch_assoc($result);
$row['message'] = 'Hello '.$row['username'];
echo(json_encode($row));

Categories