dealing with ajax response from php in jquery - php

I am trying to get the data from the array in foreach .
I am sending a ajax get request to php file and get response with json & array.
But when I try to print what inside the array its broke..
My JS code:
var url = $("#url").val();
var type = 'F';
var data_url = url + "manage/sources/ajax/ajax.php?type=GetBarber&gender=" + type ;
$.ajax({
type: "GET",
url: data_url,
dataType: "json",
success: function (response) {
// response returning - > {"status":"success","data":["name541","name214"]}
var json_obj = $.parseJSON(response);
for (i=0; i < json_obj.data.length; i++)
{
var payment = json_obj.data[i];
console.log(payment); // Just for debugging
}
}
});
I am trying to print what inside the data (names..)
Thank you for help

You have the dataType set to json therefore response is already parsed to an object. So do not call $.parseJSON
for (i=0; i < response.data.length; i++)
{
var payment = response.data[i];
console.log(payment); // Just for debugging
}

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]

Pass Json data using Jquery Ajax then display response

Why is this not working? Jquery will take the value on change and send it using ajax in json format to a php file. then same jquery will take response and append it. $(#orderSummary) never display success for me to verify that it actually get a response.
$(document).ready(function(){
$("#prodcat").change(function(){
var prodid = $(this).val();
$("#orderSummary").append(prodid);
$.ajax({
type: 'POST',
url: 'getproduct.php',
data: {'prodcat':prodid},
dataType: 'json',
success:function(response){
$("#orderSummary").append(success);
var len = response.length;
$("#product").empty();
for( var i = 0; i<len; i++){
var name = response[i]['name'];
var detail = response[i]['detail'];
var price = response[i]['price'];
$("#product").append("<option value='"+name+"'>"+name+"</option>")
}
}
});
});
});
</script>
You are appending wrong varaible
change
$("#orderSummary").append(success);
to
$("#orderSummary").append(response);
OR if you want to append success message to orderSummary then append it with ''
$("#orderSummary").append('success');

Using a dynamic variable in an ajax query

I'm struggling to pass a GET variable into a jquery file.
My code is
function upload(files){ // upload function
var fd = new FormData(); // Create a FormData object
for (var i = 0; i < files.length; i++) { // Loop all files
fd.append('file_' + i, files[i]); // Create an append() method, one for each file dropped
}
fd.append('nbr_files', i); // The last append is the number of files
$.ajax({ // JQuery Ajax
type: 'POST',
url: 'ajax/tuto-dd-upload-image.php?order=5', // URL to the PHP file which will insert new value in the database
data: fd, // We send the data string
processData: false,
contentType: false,
success: function(data) {
$('#result').html(data); // Display images thumbnail as result
$('#dock').attr('class', 'dock'); // #dock div with the "dock" class
$('.progress-bar').attr('style', 'width: 100%').attr('aria-valuenow', '100').text('100%'); // Progress bar at 100% when finish
},
xhrFields: { //
onprogress: function (e) {
if (e.lengthComputable) {
var pourc = e.loaded / e.total * 100;
$('.progress-bar').attr('style', 'width: ' + pourc + '%').attr('aria-valuenow', pourc).text(pourc + '%');
}
}
},
});
I need the 5 in url: 'ajax/tuto-dd-upload-image.php?order=5' to be the vatriable order passed through a url like domain.com/?order=XX
You can use PHP and export the variable:
var orderId = <?php echo json_encode($_GET['order']); ?>;
function upload(files) {
...
url: 'ajax/tuto-dd-upload-image.php?order=' + orderId,
Or you could parse it directly in javascript:
var orderId = self.location.search.match(/order=(\d+)/)[1];
// Then continue like the previous example
Of course you'll probably need some error checking around this, if there's a chance the GET param might ever be missing.
Try with javascript :
function $_GET(key){
var result = new RegExp(key + "=([^&]*)", "i").exec(window.location.search);
return result && result[1] || "";
}
and call $_GET(key) function in your $.ajax request.
var order = $_GET('order');
url: 'ajax/tuto-dd-upload-image.php?order='+order,

Get json value on any php page

I am creating json object but can't access its value in php.I am trying to access json object in php and assign that object to php variable.My js code is
var arr= [];
var data={ "tab" : 'system' };
jObjArr = arr.push(data);
var JSONstr = JSON.stringify(jObjArr);
what i am missing ?
I try to get tab value on that page in php.
Try to pass simple object rather than sending an array:
function send_me() {
//var arr = [];
var data = { "tab": 'system' };
//jObjArr = arr.push(data);
//var JSONstr = JSON.stringify(data);
$.ajax({
url: "a_blank.php",
type:"post",
data: data,
success: function (response) {
alert(response);
}
});
}
On php page side simply get as:
if($_SERVER["REQUEST_METHOD"]=="POST")
{
print_r($_POST['tab']);
die();
}

Iterating through a PHP-Array with $.each

I built an Ajax request with jQuery where - at the end of the PHP file, which is called - an array is the result:
echo json_encode(array('status' => 'true'));
Within my jQuery in the calling file, I would like to read if the status is true and I tried it with this:
$.ajax({
type: "GET",
url: "logic.php",
data: "receiver=" + receiverIds + "&subject=" + subject + "&msg=" + msg,
success: function(data){
$.each(data, function (i, elem) {
alert(elem.status);
});
}
});
but the alert is always undefined. When I insert this line before the $.each:
$("#additionalTextDiv").html(data);
I get the following result: {"status":"true"}
But why is the each function not working properly?
Thanks!
Change the dataType property of the options object you are setting in your AJAX call to json so the JSON string gets parsed into a JavaScript object:
$.ajax({
type: "GET",
url: "logic.php",
dataType: 'json',
...
.ajax(): http://api.jquery.com/jquery.ajax
Your $.each() loop works just fine, here is a demo: http://jsfiddle.net/54pB9/
However if you are going to loop through a lot of records a for loop will perform faster:
for (var i = 0, len = data.length; i < len; i++) {
alert(data[i].status);
}
Here is a demo: http://jsfiddle.net/54pB9/1/

Categories