I have used json_encode to encode two php arrays and now i have to read through ajax. Could anyone please let me know how to read those arrays through ajax request.
For example: i have a php file file1.php which has
echo json_encode($array1);
echo json_encode($array2);
Another file in which i read as follows:
For reading single encoded array i am reading like this
new Ajax.Request("file1.php",
{
method:'get',
asynchronous:false,
parameters: ({id: stopID, contains: tempContain}),
onSuccess:function(data){
var result=data.responseJSON;
var keys = Object.keys(result);
var values = Object.values(result);
for(var i = 0; i < keys.length; i++) {
infoString += keys[i]+":"+values[i];
}
});
You can use jquery, it will save you a lot of time ;) There are examples in this link:
http://api.jquery.com/jQuery.getJSON/
With jQuery Ajax
$.ajax({
url: '/path/to/file',
type: 'POST',
dataType: 'json',
data: {param1: 'value1'},
complete: function(xhr, textStatus) {
//called when complete
},
success: function(data, textStatus, xhr) {
//called when successful
},
error: function(xhr, textStatus, errorThrown) {
//called when there is an error
}
});
Related
As the title says, I failed to pass the data array via json ajax to php. I am using codeigniter, what did I do wrong? here is the jQuery code:
function load_page_data1(){
var data = [];
data['val'] = "solid_t1";
$.ajax({
type: 'POST',
url: BASE_URL+'index.php/Chart_varnish/getdata',
data: data,
dataType: 'json',
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error: not working");
}
});
}
Here is the php code:
function getdata(){
$parameter = '';
if(isset($_POST))
{
if(isset($_POST['val']))
{
$parameter = $_POST['val'];
} else
{
echo "failed!";
}
}
$this->load->model('Chart');
$this->load->helper('url');
$data1 = $this->Chart->getdata_solid($parameter);
echo json_encode($data1);
}
Final:
Guys, it turn out that the values did passed from jQuery to php, the problem is that I stupidly call the same php function twice within the javascript function, then the second time calling without posting the 'val', so that the php function error and stop.
Thank you all for your answers, at least I learn the different ways to passing data by using jQuery.
Don't make a array if it's not a array just make a object
var data = {};
data.val = "solid_t1";
// equivalent to
data ={val:"solid_t1"};
// equivalent to
data['val'] ="solid_t1";
$.ajax({
type: 'POST',
url: BASE_URL+'index.php/Chart_varnish/getdata',
data: data,
dataType: 'json',
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error: not working");
}
});
Update 1: if you need to send array you need to make a proper array object like below
Example :
var data=[];
item ={val:'value'};
data.push(item);
var new_data = JSON.stringify(data);
$.ajax({
type: 'POST',
url: BASE_URL+'index.php/Chart_varnish/getdata',
data: new_data,
dataType: 'json',
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error: not working");
}
});
For Debugging :
May be problem with your server side code .so for the testing purpose comment all the line in function just do this echo json_encode($_POST); and in your ajax success function just add console.log(output); and let me know the result.
create one json object
jsonObj = [];
create array list as per your need
item = {}
item ["val"] = "solid_t1";
push the array list in to the json.
jsonObj.push(item);
Please have a try like this. It is working in my case.
Your full code will be like
function load_page_data1(){
jsonObj = [];
item = {}
item ["val"] = "solid_t1";
jsonObj.push(item);
$.ajax({
type: 'POST',
url: BASE_URL+'index.php/Chart_varnish/getdata',
data: jsonObj,
dataType: 'json',
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error: not working");
}
});
}
The another way to use this is given below.
function load_page_data1(){
var jsonObj = {};
jsonObj["val"] = "solid_t1";
$.ajax({
type: 'POST',
url: BASE_URL+'index.php/Chart_varnish/getdata',
data: jsonObj,
dataType: 'json',
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error: not working");
}
});
}
Instead of var data = []; use var data = {}; to initialize your data. It should solve your problem.
Your data wasn't being passed as json, now it will.
Code will be:
function load_page_data1(){
var data = {};
data['val'] = "solid_t1";
$.ajax({
type: 'POST',
url: BASE_URL+'index.php/welcome/getdata',
data: data,
dataType: 'json',
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error: not working");
}
});
}
One more suggestion please use CI input library for post request in controller.
e.g.
$parameter = $this->input->post('val');
I'm trying to get some JSON from a php script. Bit it is failing when I try to parse it.
In the php script I use json_encode($result) and in the jQuery part I use this code:
complete: function(response){
console.log(response);
var parsed = JSON.parse(response);
var arr = [];
for(var x in parsed){ arr.push(parsed[x]);}
jQuery('#input_1_3').val(arr[1]);
jQuery('#input_1_4').val(arr[2]);
}
When I log response in the console I get this:
Object { readyState=4, responseText="{"personeelsNummer":"1",...oonplaats":"Meerhout"}0", status=200, meer...}
What am I not seeing here?
First things first:
Ensure your $.ajax has dataType: "json" as part of the settings.
$.ajax({
dataType: 'json',
//other settings
});
Second:
You are using complete. On complete, the arguments are jqXHR and textStatus. Therefore, it's not parsed there, it's the entire xhr object.
For that you have to use success. There the arguments are data, textStatus and jqXHR, and if you used the dataType as I told (and your JSON is valid), it data will be your already-parsed json.
$.ajax({
dataType: 'json',
//other settings
success: function(data, textStatus, jqXHR){
//my awesome parsed json it's on 'data'
},
error: function(jqXHR, textStatus, errorThrown){
//my awful json which failed to parse, and I can know the error on 'errorThrown'
}
});
use:
var parsed = JSON.parse(response.responseText);
response is an object with more properties than just the text content from the server request.
I'm having trouble getting JSON data sent from JavaScript to PHP. Here is my Javascript:
var noteData = {
nData: {
"postID": $postID,
"commentPar": $commentPar,
"commentValue": $commentValue
}
}
var sendData = JSON.stringify(noteData);
$.ajax({
type: "POST",
url: templateUrl+"/addnote.php",
data: sendData,
dataType : 'json',
success: function(data) {
alert(data);
console.log(sendData);
},
error: function(e) {
console.log(e.message);
console.log(noteData);
console.log(sendData);
alert("error");
}
});
Here is how I just test if the data is even being passed to PHP, it always returns back null.
<?php
$nData = json_decode($_POST['nData']);
echo json_encode($nData);
?>
What am I doing wrong?
You are sending the data as raw JSON to PHP, not as POST parameter.
There are two alternatives. The first one leaves your PHP intact:
var noteData = {
nData: {
"postID": $postID,
"commentPar": $commentPar,
"commentValue": $commentValue
}
}
var sendData = JSON.stringify(noteData);
$.ajax({
type: "POST",
url: templateUrl+"/addnote.php",
data: {
nData: sendData
},
dataType : 'json',
success: function(data) {
alert(data);
console.log(sendData);
},
error: function(e) {
console.log(e.message);
console.log(noteData);
console.log(sendData);
alert("error");
}
});
The second one modifies the PHP side alone. You need to read the input stream directly to obtain the raw data.
<?php
$nData = json_decode(file_get_contents('php://input'));
echo json_encode($nData);
This one might be slightly different depending on the server configuration. See the documentation on the input stream wrappers.
Tell your post request that you are sending json object
contentType: "application/json"
I have a problem:
I have a JS function which sending data to php script, then PHP script returning JSON data from database QUERY and I want to get values returned from PHP script.
<script type="text/javascript">
<!--
jQuery('#wysz2').submit(function() {
var myData = {
"rodzaj_konta": jQuery('#rodzaj_konta').val(),
"miejscowosc": jQuery('#miejscowosc').val()
};
jQuery.ajax({
url: 'http://somescript.php?action=results',
type: 'GET',
data: myData,
dataType: 'json',
beforeSend: function() {
jQuery('#loading').html('<p>loading...</p><img src="loading.gif" />'); //Loading image during the Ajax Request
},
error: function(xhr, textStatus, errorThrown) {
alert("Error: " + (errorThrown ? errorThrown : xhr.status));
},
contentType: "application/json; charset=utf-8",
success: function(data) {
alert(data);
}
});
return false;
});
//-->
</script>
The PHP script returning data in proper format using:
header('Content-Type: application/json');
echo json_encode($data);
When I'm trying to alert(data), I get always a null.
How to get this returned JSON data ?
EDITED:
It's strange, because I have changed sending method to POST.
PHP returning JSON:
[{"nazwa":"Test","nazwa_firmy":"Testowa","ulica":null,"numer_domy":"2A","numer_mieszkania":"11","kod_pocztowy":"00-189","miejscowosc":"Warszawa","telefon":"213-123-132","nip":"112-312-31-31","regon":"231232133","adres_www":"http:\/\/www.gogl.epl","rodzaj_uzytkownika":"serwis"}]
But my JQUERY AJAX Script still returning null.
So my script now looks like this:
<script type="text/javascript">
<!--
jQuery('#wysz2').submit(function() {
var myData = {
rodzaj_konta: jQuery('#rodzaj_konta').val(),
miejscowosc: jQuery('#miejscowosc').val()
};
jQuery.ajax({
url: 'http://somedomain.com/skrypt.php?action=wyniki_wyszukiwania',
type: 'GET',
data: myData,
dataType: 'json',
contentType: "application/json; charset=utf-8",
jsonp: "jsoncallback",
beforeSend: function() {
jQuery('#loading').html('<p>ładowanie...</p><img src="loading.gif" />');//Loading image during the Ajax Request
},
error: function (xhr, textStatus, errorThrown) {
alert("Error: " + (errorThrown ? errorThrown : xhr.status));
},
success: function (data) {
alert(JSON.stringify(data));
console.log(data);
}
});
return false;
});
//-->
</script>
Any ideas ?
you are constructing your variables while sending in a wrong way semicoluns for object names is not there according to definitions
try this
var myData = {
rodzaj_konta: jQuery('#rodzaj_konta').val(),
miejscowosc: jQuery('#miejscowosc').val()
};
and while alerting your json data try
alert(JSON.stringify(your_json_obj));
Try to alert the object of the result...
Means if json in the format {"responseCode":"001","responseMsg":"success"}
Then alert data.responseCode
In success of your ajax function try something like this
var objParams1 = $.parseJSON(data);
console.log(objParams1);
alert(objParams1.Testowa)
ajax
$('#stb_no').blur(function(){
var stb_no= $('#stb_no').val();
$.ajax({
url: "http://localhost/paymybill/ajax/stb_info",
global: false,
type: "POST",
data: {
'stb_no':stb_no, // you should give a key to the variable
},
success: function(data) {
$('#amount').val(data);
// $(".email_msg").addClass("red");
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
});
Controller code
public function stb_info(){
$stb_no=$this->mso->alldata_stbno($this->input->post('stb_no'));
echo json_encode($stb_no);
}
i am getting out put
[{"sxb_no":"xxxxxx","mzo_name":"xx","cto_name":"xxxxx","area":"xxxxx","name_sxb_owr":"","mobile_no":"xxxxxx","email":"xxxxx#yahoo.com","amount":"xxx"}]
i need to know how to get each values ex:- if i want get email id what i should i do in jquery please help me i new to ajax
Most browsers support JSON.parse(), which is defined in ECMA-262 and is the recommended way. Its usage is simple (I will use your example JSON):
var json = '{"area":"xxxxx",...,"email":"xxxxx#yahoo.com","amount":"xxx"}';
var obj = JSON.parse(json);
Note that obj.email can't be used, because you are parsing an array.
Edit: Checking your comments you need to know that the data parameter is the JSON object, parse it first and then you can do:
$('#amount').val(obj[0].email);
Just add to $.ajax call parameter dataType:"json" and Jquery will parse it in success parameter automatically. Then use it data[0]['email'];
For example :
$('#stb_no').blur(function(){
var stb_no= $('#stb_no').val();
$.ajax({
url: "http://localhost/paymybill/ajax/stb_info",
global: false,
type: "POST",
data: {
'stb_no':stb_no, // you should give a key to the variable
},
success: function(data) {
$('#email').val(data[0]['email']);
//OR
var obj = JSON.parse(data);
$('#email').val(obj[0].email);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
});