I am trying this JQuery code:
val = $(this).val();
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "?getCustomer=1&sequence="+val+"",
data: data,
success: function(data) {
alert(data["sequence"]);
}
});
but the alert is returning undefined
if i check the URL (?getCustomer=1&sequence=4) i get this returned:
[{"sequence":"53"}]
so the sequence value is definately the
this is what shows in the console:
[Object]0: Objectsequence: "112"__proto__: Objectlength: 1__proto__: Array[0]concat: concat()constructor: Array()copyWithin: copyWithin()entries: entries()every: every()fill: fill()filter: filter()find: find()findIndex: findIndex()forEach: forEach()indexOf: indexOf()join: join()keys: keys()lastIndexOf: lastIndexOf()length: 0map: map()pop: pop()push: push()reduce: reduce()reduceRight: reduceRight()reverse: reverse()shift: shift()slice: slice()some: some()sort: sort()splice: splice()toLocaleString: toLocaleString()toString: toString()unshift: unshift()Symbol(Symbol.iterator): values()Symbol(Symbol.unscopables): Object__proto__: Object
You misunderstood your json. Change
alert(data["sequence"]);
With
alert(data[0]["sequence"]);
or better
alert(data[0].sequence );
[{"sequence":"53"}] is an array, the first element of which is an object with a sequence member. You need to alert(data[0]['sequence']).
Related
These are my code:
$("#promo_form").submit(function(stay){
$.ajax ({
type: "post",
url: "<?=base_url()?>promo/code_validate",
data: $("#promo_form").serialize(),
success: function(data){
$("#myModalLabel").html(data);
}
});
stay.preventDefault();
});
And the success data result below:
$result1 = "code is invalid";
$result2 = "promo unavailable";
How can I select these and retrieve it?
This is what I did below but now working.
$("#myModalLabel").html(data->result1);
JavaScript uses dot syntax for accessing object properties, so...
$("#myModalLabel").html(data.result1);
I'll also add that you want to make sure the page at promo/code_validate prints out a JSON response, as that is how data will become an object ($.ajax is intelligent about how to parse the server's response, see the link below). So your code_validate page might look something like this:
{
"result1": "code is invalid",
"result2": "promo unavailable"
}
http://api.jquery.com/jquery.ajax/
Do this
Function controller
function code_validate()
{
echo json_encode(array('result1'=>'Code is invalid',
'result2'=>'Promo not available');
}
Javascript
$("#promo_form").submit(function(stay){
$.ajax ({
type: "post",
url: "<?=base_url()?>promo/code_validate",
data: $("#promo_form").serialize(),
success: function(data){
var mydata = JSON.parse(data);
console.log(mydata.result1);
console.log(mydata.result1);
}
});
stay.preventDefault();
});
You must return it as JSON.
Goodluck meyt
Vincent, add the dataType paramater to your ajax call, setting it to 'json'. Then just parse the response to convert it to an object so that you can access the variables easily, e.g.
in AJAX call:
dataType: "json"
in success function:
var obj = jquery.parseJSON(data);
console.log(obj);//echo the object to the console
console.log(obj.result1);//echo the result1 property only, for example
The simplest way to do what you want is create a php associative array of your values then json encode the array and echo the resulting string like this:
$response = ["result1"=>"code is invalid", "result2"=>"promo unavailable"];
echo json_encode($response);
Then on the client side, access them like this
$("#promo_form").submit(function(stay){
$.ajax ({
type: "post",
url: "<?=base_url()?>promo/code_validate",
data: $("#promo_form").serialize(),
success: function(data){
$("#modal-1").html(data.result1);
$("#modal-2").html(data.result2);
}
});
stay.preventDefault();
});
I am posting an Ajax call to a PHP function but all the data passed is "UNDEFINED". When I debugged the JQuery, the value seems work. The undefined is at server side. PHP side.
$('.js-checkout-shipping-submit').on('click', function(e) {
$.ajax({
// Change the URL to the right one
url: 'index.php?route=checkout/checkout/updateShippingAddress',
type: 'post',
dataType: 'json',
data: 'firstName:' + $(' .js-checkout-firstName').val() +
',lastName:' + $('.js-checkout-lastName').val() +
',address:' + $('.js-checkout-address').val() +
',zipcode:' + $('.js-checkout-zipcode').val() ,
success: function(data) {
if(data['status'] === "pass"){
console.log("success");
}
if(data['status'] === "fail") {
console.log("fail");
}
},
error: function(data) {
}
});
e.preventDefault();
});
public function updateShippingAddress(){
$firstName=$this->request->post['firstName'];
$lastName=$this->request->post['lastName'];
$address=$this->request->post['address'];
$zipCode=$this->request->post['zipcode'];
}
You are posting the JSON object as string, please try this
data: { // making the data to become object
firstName : $('.js-checkout-firstName').val(),
lastName : $('.js-checkout-lastName').val(),
address : $('.js-checkout-address').val(),
zipcode : $('.js-checkout-zipcode').val()
},
success: function(data) {
...
If you are getting undefined as value of post params, maybe there is jQuery selector problem.
Try to log $('.js-checkout-firstName').val() and see what you get and make shre an Input is present with class .js-checkout-firstName
You have to pass your request parameter in json format for ajax.
so your data parameter value is be like,
data: {'firstName' : $('.js-checkout-firstName').val(),'lastName' : $('.js-checkout-lastName').val(),'address' : $('.js-checkout-address').val(),'zipcode' : $('.js-checkout-zipcode').val()},
success: function(data) {
I have number of checkboxes on my page and I want to get those checkbox values in my database.
$('#assign_data').on("click",function()
{
var mandate_array = [];
var i= 0;
$('.assign_mandate:checked').each(function(){
mandate_array[i++] = $(this).val();
});
$.ajax
({
type: "POST",
url: BASE_URL+"mandate/assign_mandate.php",
data: "mandate_array="+mandate_array+"&role_id="+$('#role').val()+"&user_id="+$('#user').val(),
success: function(msg)
{
console.log(msg)
}
})
});
assign_mandate.php :
<?php
$mandate = explode(',',$_POST['mandate_array']);
// print_r($mandate); //it shows the data in array
count($mandate);exit; // it does not show the count in console
?>
When I print the array it show me the array data in console but when I try to echo the count of array it shows blank. Why ?
Thanks in advance
You have to echo the variable count value.
<?php
$mandate = explode(',',$_POST['mandate_array']);
// print_r($mandate); //it shows the data in array
echo count($mandate);exit; // it does not show the count in console
?>
Use JSON.stringify.
You would typically convert the array to a JSON string with JSON.stringify, then make an AJAX request to the server, receive the string parameter and json_decode it to get back an array in the PHP side.
$('#assign_data').on("click",function()
{
var mandate_array = [];
var i= 0;
$('.assign_mandate:checked').each(function(){
mandate_array[i++] = $(this).val();
});
$.ajax
({
type: "POST",
url: BASE_URL+"mandate/assign_mandate.php",
data: "mandate_array="+JSON.stringify(mandate_array)+"&role_id="+$('#role').val()+"&user_id="+$('#user').val(),
success: function(msg)
{
console.log(msg)
}
})
});
mandate_array is Array so you wont posted array data in query string, you should use JSON.stringfy() function to convert array/JSON object into string.
$.ajax
({
type: "POST",
url: BASE_URL+"mandate/assign_mandate.php",
data: "mandate_array="+JSON.stringfy(mandate_array)+"&role_id="+$('#role').val()+"&user_id="+$('#user').val(),
success: function(msg)
{
console.log(msg)
}
})
In PHP code
var_dump(json_decode($_POST['mandate_array']));
Use echo in front of the count()
I am trying to use jQuery sortable and then save the changes to the database, however before I even get to updating the database I have something strange going on that I can't fathom. If I log the serialised data to the console, I get all items in the 'list' but if I echo out the json encoded array from the php script I only get one item - confused.com.
The jquery at the moment is:
$('#sortable-list').sortable({
//handle : '.handle',
update : function () {
var order = $(this).sortable('serialize');
var table = $(this).parent().attr('id');
console.log(order);
$.ajax ({
type: "POST",
url: templateDir + "/inc/changeSortOrder.php",
data: "order=" + order + "&sort=1&sort_table=" + table,
dataType: "json",
cache: false,
success: function(data)
{
console.log(data);
}
});
}
});
The PHP at the moment is:
if (isset($_POST['sort']) && $_POST['sort'] == 1) {
if ($_POST['sort_table'] == 'nationalities') {
$output = array();
$list = parse_str($_POST['order'], $output);
echo json_encode($output);
}
}
The console log gives me:
nationality[]=17&nationality[]=1&nationality[]=47&nationality[]=23&nationality[]=3&nationality[]=4&nationality[]=5&nationality[]=6&nationality[]=7&nationality[]=8&nationality[]=12&nationality[]=10&nationality[]=11&nationality[]=13&nationality[]=14&nationality[]=15&nationality[]=16&nationality[]=18&nationality[]=19&nationality[]=20&nationality[]=21&nationality[]=22&nationality[]=24&nationality[]=25&nationality[]=26&nationality[]=27 etc
And the echo json gives me:
Object {nationality: Array[1]}
nationality: Array[1]
0: "17"
length: 1
So for some reason the full array isn't being passed through to the PHP file and I can't work out why.
Your problem is that you are trying to assign a serialized array, to a single query string parameter, which will yield an incorrect query string. Try passing the serialized list as returned by the plugin serialize method like so:
$.ajax ({
type: "POST",
url: templateDir + "/inc/changeSortOrder.php",
data: order + "&sort=1&sort_table=" + table,
dataType: "json",
cache: false,
success: function(data)
{
console.log(data);
}
});
And then access the passed list in php with:
$list = $_POST['nationality'];
I trying to post some value via ajax to php then php print send back js console.log, have problem:
build array( I'm doubt below I made is array??)
$('.eachcontainer').each(function(){
var arr = $(this).find('img').map(function(){
return $(this).attr('src');
});
console.log(arr);
// result:
// ["16.png", "17.png", "19.png", "18.png"]
// ["0.png"]
// ["0.png"]
// []
// []
$.ajax({
type: "POST", url: "update.php",
data: arr
}).done(function(msg){
console.log(msg);
});
});
php
print_r($_POST);
js come back console.log
Array
(
[undefined] =>
)
Array
(
)
Array
(
)
Array
(
[undefined] =>
)
Why this does not work? How can i fix it?
Also, I tried to change the syntax in my ajax function data: {arr: arr} but this didn't work either.
Error message:
TypeError: Type error jquery-1.10.1.min.js:6
Found error line in jquery-1.10.1.min.js:6:
t = x.isFunction(t) ? t() : null == t ? "" : t, i[i.length] = encodeURIComponent(e) + "=" + encodeURIComponent(t)
you haven't constructed proper key&value pair using your data, if you want to pass a raw stream of data then set processData: false and capture with php://input
var arr = $(this).find('img').map(function(){
return $(this).attr('src');
});
$.ajax({
type: "POST", url: "update.php",
data: arr,
processData: false,
}).done(function(msg){
console.log(msg);
});
on the php side
$data = file_get_contents("php://input");
You first need to call arr.get() to get the jquery.map result back as a regular javascript array. Then you can pass it to the ajax data paramter as:
data: { "images" : arr.get() }
So the full ajax call would look like this:
$.ajax({
type: "POST", url: "update.php",
data: { "images" : arr.get() }
}).done(function(msg){
console.log(msg);
});
You can then read the array back in php as:
$images = $_POST['images'];