fetch data from JSON in PHP - php

I have a JSON code that send a form to on PHP file and I want to use data in PHP
the code is:
// add button .click
$('a.add').click(function(){
$('#loader').show();
var url = "/yadavari/test.php?";
var json_text = JSON.stringify($("form[name='add']").serialize(), null, 2);
var datas = JSON.parse(json_text);
ajx = $.ajax({
url: url,
type: 'post',
data: datas,
dataType: 'json',
success: function(r) {
$('#loader').hide();
if(r.r != 0){
alert("ok");
jsmsalert($('#alert_add'),'success',r.m);
apendtable(r.r);
$("tr").removeClass("odd");
$("tr.viewrow:odd").addClass("odd");
$("tr.editrow:odd").addClass("odd");
$('td[colspan="7"]').remove();
}
else{
jsmsalert($('#alert_add'),'error',r.m,0);
}
},
error: function(request, status, err) {
$('#loader').hide();
jsmsalert($('#alert_add'),'error','error msg');
alert( "ERROR: " + err + " - " );
}
Now I want to fetch data from this JSON code in my PHP page.
I searched but every body just said that $string='{"name":"John Adams"}'; and so.
But I dont know that how can I have this $string in my PHP.

You should have something like:
<?php
echo $_POST["INPUTNAME"];
?>
Care about this, it suffers from security injection.

You need to call the php json_decode function on the returned string. This will convert it into an associative array:
$json2array = json_decode($json_text);
echo $json2array['name']; // "John Adams"

Related

I have arrays stored in a json object, I send them using ajax call to the server side, how to access the data?

$scope.addQunatity = function(){
var url="../php/mainPageFacture.php";
// store data from user in the js arrays
var quan_cls_crt=[$("#quan_cls_crt").val(),$("#quan_cls_crt2").val()];
var quan_piece=[$("#quan_piece").val(),$("#quan_piece2").val()];
var itemName=[$("#designList").val(),$("#designList2").val()];
var dechargementNote=[$("#dechargementNote").val(),$("#dechargementNote2").val()];
var itemIds=[78,75];
var func="addQunatity";
var data = {"function": func,
"quan_cls_crt":quan_cls_crt,
"itemId":itemIds,
"dechargementNote":dechargementNote,
"quan_piece":quan_piece};
data = JSON.stringify(data);
var options = {
type : "get",
url : url,
data: {data:data},
dataType: 'json',
async : false,
cache : false,
success : function(response,status) {
debugger;
$scope.getAllItemNames();
alert("success");
},
error:function(request,response,error){
alert("Error: " + error + ". Please contact developer");
}
};
$.ajax(options);
}
Here is my php code that will receive the Json object
function addQunatity(){
$quan_cls_crt = $_GET["quan_cls_crt"];
$quan_piece = $_GET["quan_piece"];
$itemId=$_GET['itemId'];
$dechargementNote=$_GET['dechargementNote'];
}
I expect to receive the json arrays and store them in php variable in order to use the in the query later on, but i have no idea how to access the arrays in the json object
You don't have to stringify the data, just send it as it is - the json data type causes jQuery to JSON-encode it for you. Don't make another object.
var data = {"function": func,
"quan_cls_crt":quan_cls_crt,
"itemId":itemIds,
"dechargementNote":dechargementNote,
"quan_piece":quan_piece};
var options = {
type : "get",
url : url,
data: data,
dataType: 'json',
async : false,
cache : false,
success : function(response,status) {
debugger;
$scope.getAllItemNames();
alert("success");
},
error:function(request,response,error){
alert("Error: " + error + ". Please contact developer");
}
};
$.ajax(options);
}
<?php
$received_data = file_get_contents('php://input');
$data = json_decode($received_data);
//Here now you can access
$variable_name = $data['keyname']; //this means instead of $_GET or $_POST or $_REQUEST
?>
You can access received json data to php using the file_get_contents('php://input'); method..
Dont stringify the data. Use your same code and remove the stringify line.
var url="../php/mainPageFacture.php";
// store data from user in the js arrays
var quan_cls_crt=[$("#quan_cls_crt").val(),$("#quan_cls_crt2").val()];
var quan_piece=[$("#quan_piece").val(),$("#quan_piece2").val()];
var itemName=[$("#designList").val(),$("#designList2").val()];
var dechargementNote=[$("#dechargementNote").val(),$("#dechargementNote2").val()];
var itemIds=[78,75];
var func="addQunatity";
var data = {"function": func,
"quan_cls_crt":quan_cls_crt,
"itemId":itemIds,
"dechargementNote":dechargementNote,
"quan_piece":quan_piece};
var options = {
type : "get",
url : url,
data: {data:data},
dataType: 'json',
async : false,
cache : false,
success : function(response,status) {
debugger;
$scope.getAllItemNames();
alert("success");
},
error:function(request,response,error){
alert("Error: " + error + ". Please contact developer");
}
};
$.ajax(options);
}
In the PHP side, like you have done -
$quan_cls_crt = $_GET["quan_cls_crt"];
$quan_piece = $_GET["quan_piece"];
$itemId=$_GET['itemId'];
$dechargementNote=$_GET['dechargementNote'];
And to access each of the values from array you can simply do that with $quan_cls_crt[0] or $quan_cls_crt[1]

Read data from mysql php jquery ajax

I need to read data from my web page with jquery + ajax
This is my function:
public function getvalueshahr()
{
if($_POST['ostan']!=0){
$db= JFactory::getDbo();
$query=$db->getQuery(TRUE);
$query->select('id,title')->from('#__categories')->
where($db->quoteName('parent_id').'='.$db->quote($_POST['ostan']));
$db->setQuery($query);
$res=$db->loadObjectList();
echo $db->getErrorMsg();
echo json_encode($res);}
}
I can read data with c# like this:
But my ajax method is not working. Here is the method:
$.ajax({
type: "POST",
url: "www.mysite.net/index.php?task=shahrestan.getvalueshahr",
data: "{ostan=77}",
dataType: "json",
success: function (result)
{
var d = $.parseJSON(result);
$.each(d, function (i, field)
{
$("#output").append("id: " + field.id + " title: " +
field.title+"br/>");
});
},
error: function (e)
{
alert("error:" + e.responseText);
}
});
The method returns nothing.
You're sending a string instead of an object in your ajax-request. Try changing :
data: "{ostan=77}"
to
data: { ostan: 77 }
And you should set the content type before echoing the results in PHP:
header('Content-Type: application/json');
echo json_encode($res);
Now you don't need $.parseJSON in the JS-code. You will get a json-object straight away.
First of all you send a wrong data to the server. You have to rewrite part of your code like this:
data: {ostan: 77},
or
data: "ostan=77",
The second problem is you get a result as a json object on the success method, but you try to parse it again to the json object. So remove this line from your code:
var d = $.parseJSON(result);
Finally your ajax function should looks like this:
$.ajax({
type: "POST",
url: "www.mysite.net/index.php?task=shahrestan.getvalueshahr",
data: {ostan: 77},
dataType: "json",
success: function (result)
{
$.each(result, function (i, field)
{
$("#output").append("id: " + field.id + " title: " +
field.title+"br/>");
});
},
error: function (e)
{
alert("error:" + e.responseText);
}
});
If you are loading data from you mysql-database you eventually have to convert these data because it is not stored as utf-8 converted. This piece of code convert given object to UTF-8: mb_convert_encoding(database-entry,'UTF-8');

$.ajax POST not working correctly php

Hi i'm trying to get this with jquery ajax but don't know if i'm doing it correctly...
Really tried everything and basically had to look at jquery.ajax for dummies but still not getting it to work...
function addMix(mix) {
alert(mix);//Here I get my array of int's
var myArr = JSON.stringify(mix);
$.ajax({
type:"POST",
dataType: "json",
url: "add.php",
data: myArr,
success: function(data) {
alert("Success: " + data);
console.log(data);
},
error: function(x,y,z){
alert("Error: " + x + ", " + y + ", " + z);
console.log(x, y, z);
},
complete: function(data){
alert("Complete: " + data);
console.log(data);
}
});
}
the php:
<?php
header('Content-Type: application/json');
include "con.php";
$mix = json_decode($_POST);
foreach($mix as $index => $val){
$temp = array();
foreach($temp[$index] as $key => $value){
array_push($temp, $value);
}
}
$sql = "INSERT INTO mg_test(value)
VALUES('$temp')";
mysql_query($sql);
echo json_encode($temp);
mysql_close($con);
?>
Only thing im getting in return is,
alert(mix) = 2,1,3,2
Success: null
Complete: [object Object]
And I get nothing in the DB...
Could anyone point me in the right direction? What am I doing wrong?
Why do you do JSON.stringify(mix) in the $.ajax call?
You can just put the object / array or what it is there!
Here's a fixed JS:
function addMix(mix) {
$.ajax({
type:"POST",
dataType: "json",
url: "add.php",
data: { mix: mix }, // <--- this
success: function(data) {
alert("Success: " + data);
console.log(data);
...
});
}
And in PHP, you must use
$mix = json_decode($_POST['mix']);
instead of:
$mix = json_decode($_POST);
Also, I am pretty sure this query won't work:
$sql = "INSERT INTO mg_test(value) VALUES('$temp')";
$temp is an array - you will have to build the query of it, not just put it there and hope it will magically work. It won't.
Based on $.ajax documentation:
The data option can contain either a query string of the form
key1=value1&key2=value2, or an object of the form {key1: 'value1',
key2: 'value2'}.
Just skip the stringify and pass the object as it it in the data field.
You are sending data to ajax call wrongly. Donot use JSON.stringify(), instead send request parameters like this.
type:"POST",
dataType: "json",
url: "add.php",
data: { "requestData": mix },
success:function(data){
console.log(data);
}
In PHP file. get this as
$mix = json_decode($_POST['requestData']);
dont alert an object alert("Complete: " + data); it (as you see) returns [Object Object]. so what says the console.log(data);?
If you want to see your objects while using
console.log(data);
It would be much better readable in Google chrome console.

jquery ajax sending json to php error

Okay so here is my ajax request:
$("#scoreForm").submit(function(e){
e.preventDefault();
var nickName = $('#nickName').val();
var gameScore = parseInt($('#gameScore').text());
var result = { 'result' : '{ "nick":"'+nickName+'", "score":'+gameScore+' }' };
//var result = { "nick":nickName, "score":gameScore };
$.ajax({
url: "http://localhost:8888/snake/addScore.php",
type: "POST",
data: result,
//dataType: "jsonp",
success: function(data){
alert("siker");
},
error: function(jqXHR, textStatus, errorThrown) {
alert("bukta " + textStatus);
//console.log(data);
}
});
return false;
});
and my php process code:
$json_decoded = json_decode($_POST['result'],true);
//$nick = $_GET['nick'];
//$score = $_GET['score'];
$mysqli = new mysqli("localhost", "root", "root", "snake",8889);
//$mysqli->query("INSERT INTO scores(nickName,score) VALUES('".$nick."', ".$score.")");
$mysqli->query("INSERT INTO scores(nickName,score) VALUES('".$json_decoded['nick']."', ".$json_decoded['score'].")");
echo "true";
Now i got the data inserted into the database, but ajax still firing error event. i read that if i set the dataType to jsonp it will go trough , but then i get parse error, how do i get past that?
Wehn you access the $_POST variables in your php script, you need to refer to them the way they are packaged with the JSON object:
$_POST['nick']
$_POST['score']
If you want to refer to the items as $_POST['result'] and use your json decoding approach, youll need to package it this way:
var result = { result : { "nick":nickName, "score":gameScore } };

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);
}
});
}

Categories