Struggling to decode JSON in jquery ajax success callback from PHP script - php

I've been trying to find an answer for this for hours but really struggling.
I have a simple jquery Ajax function which sends data to a PHP script. The data is then used to conduct a MySQL query and the results are included as an array. I'm sending the array back using json_encode but can't work out how to display the array at the other end. I've posted the code below. The console.log is displaying Object {modules: Array[0]}
. There should be 3 entries in the array.
The PHP
<?php
include_once('../../dbconnect.php');
$name = $_POST['uploadname'];
$query = "SELECT * FROM marking_assignments WHERE name = '$name'";
$details = $conn->query($query);
$modules = array();
while ($row = $details->fetch_assoc()){
$modules[] = $row['unit'];
}
$dataarray = array("modules"=>$modules);
echo json_encode($dataarray);
?>
The jQuery
var uploadname;
$("#uploadname").blur(function(){
uploadname = $(this).val();
$.ajax({
url: "uploadnames.php",
type: "POST",
data: {uploadname: uploadname},
dataType: 'json',
success: function(data){
console.log(data);
}
});
});

you should use:
var parsedData = jQuery.parseJSON(data);
and then:
console.log(parsedData)

Related

Getting data from php using ajax not working

I am trying to make an Ajax request and get the data from a PHP file; that is, a single row based on a where condition. I don't know how to extract the PHP array in JavaScript.
My Ajax code:
function loadData(Sno)
{
$.ajax({ //create an ajax request to
type: "GET",
url: "php/getgreetings.php?loadsno=" + Sno,
dataType: "json", //expect html to be returned
success: function(data){
response = jQuery.parseJSON(data);
alert (response.Greet_Name);
}
});
}
My PHP code:
require('db.php');
$loadsno = $_GET['loadsno'];
$query = "SELECT * from Greetings where greetsno=".$loadsno ;
$result = sqlsrv_query($conn,$query);
$data = array();
while ($row = sqlsrv_fetch_array($result))
{
$data[] = $row;
}
echo (json_encode($data));

how to return an array in AJAX call in php

I have a form that has a select option , So I am trying to update the form/table with some content from database when I select a type in the select option ,
SO for that I did an ajax call something like this.
$("#selectPlantilla").on("change",function(){
var descripcion = $(this).val();
//alert(descripcion);
var url="http://index.php";
var posting = $.post(url, {
im_descripcion: descripcion,
}).done(function (data) {
alert(data);
});
});
And then I validated the call in php on the same inde.php page like this
if(isset($_POST['im_descripcion']))
{
$db = new dataBase();
$result = $db->execute("SELECT * FROM `tableNmae` WHERE `descripcion` = '".trim($_POST['im_descripcion'])."'");
$result = mysql_fetch_array($result);
print_r($result);
}
The problem I am facing is in the alert window it return the whole page instead of just the $result that I have printed , So can any one help me out how I can channelize it properly , I have use the values from the array $result to update in the form using JQuery .
Thanks in Advance
For returning PHP array data in Ajax, JSON will make your life the simplest.
$result = mysql_fetch_array($result);
echo(json_encode($result));
This will return the array in a format that is easily usable by JavaScript. Try this to see its content:
alert(JSON.stringify(data));
With JSON, you should be able to fetch data or iterate through it in JavaScript
Try this
In Javascript
<script type="text/javascript">
var $ =jQuery.noConflict();
$(document).ready(function(){
$('.dropdown_class').on('change', function() {
var m_val = this.value;
var datastring = "im_descripcion="+m_val;
$.ajax({
type: "POST",
url: "lunchbox_planner.php",
data: datastring,
cache: false,
success: function(result) {
var v = $.parseJSON(result);
var l = v.length;
for(var i=0;i<l;i++){
var sh_d = "<div class='coco3'>"+v[i]+"</div>";
$('.mon_tea').append(sh_d);
}
}
});
});
});
</script>
<div class="mon_tea">
In PHP
<?php
if(isset($_POST['im_descripcion'])) {
$db = new dataBase();
$result = $db->execute("SELECT * FROM `tableNmae` WHERE `descripcion` = '".trim($_POST['im_descripcion'])."'");
while($row_sh = mysql_fetch_array($result)){
$all_incr[] = $row_sh['col_name'];
}
echo json_encode($all_incr);
}
?>

echo json_encode() not working via ajax call

I really don't know what i'm missing here. I have this script:
<script type="text/javascript">
function ServiceOffer(){
var service_name = $('#service_name').val(),
dataString = "service=" + service_name;
$.ajax({
type: "POST",
url: "posted.php",
data:dataString,
success:function(data){
console.log(data);
}
});
}
$(document).ready(function(){
ServiceOffer();
$(document).on('change','#service_name',function(){
ServiceOffer();
});
});
</script>
And here is my code for posted.php
<?php
$connect = mysql_connect('localhost','root','') or die('Unable to connect'.mysql_error());
$select = mysql_select_db('hcs',$connect) or die('Unable to select database'.mysql_error());
$service = $_POST['service'];
$query = mysql_query("SELECT * FROM serviceoffer WHERE servicename = '$service'");
$num = mysql_num_rows($query);
while($rows = mysql_fetch_array($query)){
$data[] = $rows;
}
echo json_encode($data);
So what i'm missing? I don't think there is a string that is being attached in my code and it gives me string in my console and not json encoded data. Please Help! Thanks!
Edit: Here is the data that is being returned in my console.
You have three options:
Add dataType: 'json' to the options in $.ajax.
Add header("Content-type: application/json"); to the PHP code.
Use console.log($.parseJSON(data)) in the success function.
Note that you shouldn't use option 3 if you've also used options 1 or 2. jQuery automatically parses the JSON in the first two cases, and you'll try to parse the result of that, which won't work.
At a minimum, you should send the appropriate header in PHP, eg
header('Content-type: application/json');
echo json_encode($data);
exit;
You can also set the dataType in jQuery's $.ajax method to specify the expected response type. I also find it easier to send request parameters as object literals (saves having to build URL encoded strings), eg
$.ajax({
type: 'POST',
dataType: 'json',
data: { service: service_name },
//etc
Update
As shirejedi mentioned, you should initialise $data as an array
$data = array();
while($rows = mysql_fetch_array($query)){
$data[] = $rows;
}

Undefined index in PHP post with AJAX

In my local machine, I am trying to save data from a json to my mysql database, I am using Wampserver.
In my html page (saveInfo.php), I have this jquery code:
<script type="text/javascript">
var jsObj = {"user_id":5, "login":"hsm"};
var jsonobj = JSON.stringify(jsObj);
$.ajax({
type: "POST",
url: "json_handler.php",
data: { 'jsonobj':jsonobj },
success: function(){
alert('success');
window.location = "http://localhost/quranMapping/php/json_handler.php";
}
});
</script>
In the other side, I have my server-side php code (json_handler.php) like that:
<?php
$input = file_get_contents('php://input');
$input = $_POST['jsonobj'];
$result = json_decode($input);
echo $result->user_id;
?>
But when I run that code, I get this error:
You should remove this:
var jsonobj = JSON.stringify(jsObj);
and change
data: { 'jsonobj':jsonobj },
to
data: jsObj,
On the php side to decode the data just use
$user_id = isset($_POST["user_id"])?$_POST["user_id"]:"";
$login = isset($_POST["login"])?$_POST["login"]:"";
Also there is no need to do
$input = file_get_contents('php://input');
Since the form is being posted with an object as data the value will be application/x-www-form-urlencoded so it don't be valid json.

jQuery AJAX type: 'GET' make problems with PHP

I tried until this morning to retreive data from Mysql and ajax.
This is my code :
HTML :
$.ajax({
//type:'GET',
url: "/lecture_message_pilote.php",
data: ({location_id:zlid}),
contentType: "application/json; charset=utf-8",
dataType: 'json', //data format
success: function(data) //on recieve of reply
{
var zidpilote = data[0]; //get id
var zmessage = data[1]; //get name
alert(zmessage);
}
});
And PHP :
$result = mysql_query("select * from Test_phoneGAP_message where IDPILOTE = '".$location_id."'");
$array = mysql_fetch_row($result);
echo (json_encode($array));
mysql_close();
I've the error message : UNDEFINED for alert(zmessage);
If I use the PHP request :
$result = mysql_query("select * from Test_phoneGAP_message");
I have a good result. I think my PHP don't take the $location_id.
try to access the parameter via the $_REQUEST["location_id"] element of php.
i.e.
$result = mysql_query("select * from Test_phoneGAP_message where IDPILOTE = '".$_REQUEST["location_id"]."'"); $array = mysql_fetch_row($result);

Categories