I have One Program where i get information contains in array and i want to aceess it with using key.
Is there any Way for this ?
Here are code example :
jQuery("#sl_name").change(function(){
var id = this.value;
jQuery.ajax({
url : 'insert.php',
type:'post',
data:{'action': 'getById','id':id},
success : function(data){
alert(data);
}
});
});
Here variable Data contain array of user i need to access by key value like in php we can get.
If you are return print_r than use json_encode method.
Thanks In Adavance.
don't use alert to debug objects, you will always get [Object object], use console.log instead:
jQuery("#sl_name").change(function () {
var id = this.value;
jQuery.ajax({
url: 'insert.php',
type: 'post',
data: {
'action': 'getById',
'id': id
},
success: function (data) {
console.log(data);
//if data is not yet a json object
data = JSON.parse(data);
//To access by key/prop
console.log(data.username);
//if data is an array:
for (var i = 0; i < data.length; i++) console.log(data[i]);
}
});
});
Related
I'm trying to put together a working demo (including mysql) of a form that uses jquery to serialize form data and php to retrieve the data so that it can be passed to a mysql query.
The form seems to be posting data correctly but I'm not sure how to set up the processing script which sees $_POST to unserialize the data so that I can pass it to mysql. You can see the demo at http://www.dottedi.biz/demo/code/ajax/serialize .
I have tried using:
$data=unserialize($_POST['data']);
to unserialize the data but it comes back empty. A simple print_r ($_POST); returns the array data from the form. You can see that if you test the demo. Suggestions please?
Added info - the contents of the script.js file:
$(document).ready(function() {
$('form').submit(function(evt) {
evt.preventDefault();
$.each(this, function() {
var input = $(this);
var value = input.val();
var column = input.attr('name');
var form = input.parents('form');
var linked_col = form.find('#associated').attr('name');
var linked_val = form.find('#associated').val();
// var serializedData = $(this).serialize();
$("#Status").html( "" );
$.ajax({
url: "update.php",
data: {
val: value,
col: column,
id: linked_col,
id_val: linked_val
},
type: "POST",
success: function(html) {
$("#Status").html( html );
}
});
});
});
});
9/22 - shortened script.js
$(document).ready(function() {
$('form').submit(function(evt) {
evt.preventDefault();
$.each(this, function() {
$("#Result").html( "" );
$.ajax({
url: "update.php",
data: $('form').serialize(), // works to post data
type: "POST",
success: function(html) {
$("#Result").html( html );
}
});
});
});
});
Comment - I tested and it seems that the same data is posted using serialize as above vs creating a variable like var serializedData = $(this).serialize() and posting the variable, but this is shorter.
Perhaps you should
$('form').submit(function(evt) {
// Serialize the data in the form
var serializedData = $(this).serialize();
//send off serializedData in your ajax
}
THEN
php script will have
$data=json_decode($_POST['data']);
NEW WAY
$.ajax({
url: "update.php",
data: {'data': $('form').serialize()}, // works to post data
type: "POST",
success: function(html) {
$("#Result").html( html );
}
Here's what I want to do. User submits form (a single text input) and send to PHP. PHP returns this;
{"status":"true","custid":"00001","custname":"John"}
I know that it is in JSON format, but I don't know how to catch and use the value so I can us the returned values.
$(function(){
$('#icnumber-form').submit(function(){
var icno = $('#icnumber').val();
var purl = 'php/create_process.php'
$.ajax({
type : 'POST',
url : purl,
cache : false,
data : icno,
dataType: 'json',
success : function(response){
var json = $.parseJSON(response);
alert(json.message);
},
beforeSend:function(){
$('.cust-exist-view').show();
}
});
return false;
})
});
Since you set the dataType to json, the response comes back as an already parsed object, so you don't try to parse it yourself.
success : function(response){
alert(response.status);
},
You don't need to use var json = $.parseJSON(response); because jQuery automatically parse the JSON string to object . Just use it as a javascript object to access the json properties. I create a simple demo from your code. View it in jsfiddle
JS Code:
$(function () {
$('#icnumber-form').submit(function () {
//var icno = $('#icnumber').val();
var purl = '/echo/json/'
$.ajax({
type: 'POST',
url: purl,
cache: false,
data: {
json: '{"status":"true","custid":"00001","custname":"John"}',
delay: 1
},
dataType: 'json',
success: function (response) {
alert( "status:" + response.status
+ "\ncustname:"+response.custname
+ "\ncustid:"+ response.custid);
},
beforeSend: function () {
// $('.cust-exist-view').show();
}
});
return false;
})
});
SO you just need to view this part to see how to use json return :
success: function (response) {
alert( "status:" + response.status //access status
+ "\ncustname:"+response.custname //access custname
+ "\ncustid:"+ response.custid); // access custid
},
I am sending a value to mysql query throught ajax. I get output from query as array. I used echo json_encode($var);
If my array size is more than 1, my success function is not getting called. I could see the response and status code 200 in fire bug.
How should I retrieve the value in my success function ?
success: function(data){
ob = jQuery.parseJSON(data);
}
Update
my Json response from firebug
{"uid":"4",
"name":"ram\u00fcrmeg\u00f6zl\u00fcer",
"pic_big":"http:\/\/profile.ak.fbcdn.net\/hprofile-ak-prn1\/4149__3333_n.jpg"}
$.ajax({
type: "POST",
url: "x.php",
dataType: 'json',
data: y,
success: function(data){
}
})
Try the below and see if you get any alert.
if(!$.isEmptyObject(data))
{
alert (data);
var len = data.length;
for (var i = 0; i< len; i++) {
var var1 = [data[i].uid];
var var2 = [data[i].name];
var var3 = [data[i].pic_big];
}
else{alert('No data')}
Your response is already an Object, no need to parseJSON it. Just do this for getting the values:
console.log(data.uid);
console.log(data.name);
console.log(data.pic_big);
Or whatever you wanna do with those values.
You can try:
$.ajax({
type: "POST",
url: "x.php",
dataType: 'json',
data: y,
success: function(data){
$.each(data, function() {
var uid = this.uid; // etc
}
// this works alone if your response is wrapped in [ ], if not:
if(!data.length) {
var uid = data.uid;
} else { // above $.each code
}
}
jsFiddle of this here: http://jsfiddle.net/Y73xe/
I would like to send some data by using jquery ajax function to my PHP file.
I have created such function:
function ajax_call (url, select, select_name)
{
$(select).change(function () {
$(".result").fadeIn(400).html('<img src="ajax-loader.gif"/>');
var select_value = $(this).val();
$.ajax({
type: 'POST',
url: url,
data: { select_name : select_value },
success: function(data){
$(".result").html(data);
}
});
});
}
I call it:
ajax_call ('url path to my PHP file', '#my_select_div', 'my_data_name');
I have problem with this part:
data: { select_name : select_value }
I would like to get:
$_POST['my_data_name']
but I'm getting:
$_POST['select_name']
Any ideas?
Thanks for your answers.
When using object literal syntax, the key can be a string or an identifier. The identifier represents the key name, not a variable. You have to assign the key/value after creating the object if you want to use variable key names.
var data = {};
data[select_name] = select_value;
$.ajax({
type: 'POST',
url: url,
data: data
I have an ajax call to a php file that encodes the array into a json array/object. What I am trying to do is to print the json response into a table format or an array of
div's. I am stuck on how to handle the response on ajax success. Here is my ajax..
<script>
$(document).ready(function(){
$("#adapter").keyup(function()
{
var adapter = $(this).val();
var dataString = 'searchword='+ adapter +'&format=json' ;
if(adapter=='' || adapter < 2 )
{
$("#display3").hide('');
}
else
{
$.ajax({
type: "POST",
url: "ajax/phpfile",
data: dataString,
cache: false,
success: function(data)
{
var myObj = data;
///NOT how to print the result and decode in html or php///
}
});
}return false;
});
});
</script>
Here is the json response back from the server. I can alert the whole json response, so I know it is working on the ajax side...
{"Result":[{"ptos":{"PTOMasterID":"1","PTOMasterPart":"828B-U6805-L1CX","PTOSeriesUniqueID":"22","PTOPrice":"2715.78","PTOSeries":"82","PTOMounting":"8B","PTOTransmission":"U68","PTOSpeed":"05","PTOShifter":"L","PTOAssemblyID":"1","PTOShaftID":"C","PTOSpecialFeature":"X","PTODate":"2011-11-30 17:28:10"}},{"ptos":{"PTOMasterID":"2","PTOMasterPart":"828B-U6805-L3CX","PTOSeriesUniqueID":"22","PTOPrice":"2715.78","PTOSeries":"82","PTOMounting":"8B","PTOTransmission":"U68","PTOSpeed":"05","PTOShifter":"L","PTOAssemblyID":"3","PTOShaftID":"C","PTOSpecialFeature":"X","PTODate":"2011-11-30 17:28:10"}]}
$(document).ready(function(){
$("#adapter").keyup(function()
{
var adapter = $(this).val();
var dataString = 'searchword='+ adapter +'&format=json' ;
if(adapter=='' || adapter < 2 )
{
$("#display3").hide('');
}
else
{
$.ajax({
type: "POST",
dataType: "json", //set this to json
url: "ajax/phpfile",
data: dataString,
cache: false,
success: function(data)
{
var myObj = data;
///NOT how to print the result and decode in html or php///
console.log(myObj); //to see the object
}
});
}return false;
});
});
Alternatively you could use JSON2.js like so
JSON.parse(text, reviver)
JSON 2 GITHUB
You need to declare a dataType: "JSON" if you're going to return JSON data from an ajax call. Then it's just var pto_id = data.ptos.PTOMasterID and you can do a $(object).html(pto_id); to put in the value. Hope that answers the questions you were looking for.
Interesting question-- I found this online. It should be able to iterate over all the objects and all the properties of the objects.
http://www.openjs.com/scripts/others/dump_function_php_print_r.php