Read encoded data in ajax request - javascript

My ajax retrieves the following response in the console:
PHP
$checkout_session_data = json_encode(['id' => $checkout_session->id]);
wp_send_json_success( $checkout_session_data );
// this is then retuend to the JS ajax function.
data: "{\"id\":\"cs_test_a1SOgBGIPsRrECu5pP8TDCW16JYMMHnGnmfh7Lp6qf8bvwTk3hK97sI7e7\"}"
success: true
I'm unclear how to get the ID value from the response from within the .done part of my ajax function.
.done( function(response) {
if( response.success == true ) {
console.log(response);
}
Attempts:
console.log(response.data.id);
console.log(response[0].id);

Your data is double encoded, wp_send_json_success encodes the data passed to it to JSON so do not json_encode your data before you pass it to wp_send_json_success,
$checkout_session_data = ['id' => $checkout_session->id];
wp_send_json_success( $checkout_session_data );
.done( function(response) {
if( response.success == true ) {
console.log(response.data.id);
}
}

Instead of using the ajax request, you would be better served by using the getJSON function here. A sample of the code is shown below.
$.getJSON( "ajax/test.json", function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
});
You can find further details from this link https://api.jquery.com/jquery.getJSON/

Related

passing arrays in jquery post request not working

im trying to pass javascript arrays in a jquery .post, but it's not showing on the page. What am i doing wrong? i see that my arrays are filled, but the data is not showing on the page post. The console log shows the p element also i dont know why it's doing that.
jquery code:
$("#submitboeking").click(function(event) {
event.preventDefault();
//Cursisten
var voornamen = [];
var achternamen = [];
var geslachten = [];
var geboortedata = [];
$("[id^='txtCursistVoornaam']").each(function() {
voornamen.push($(this).val());
});
$("[id^='txtCursistAchternaam']").each(function() {
achternamen.push($(this).val());
});
$("[id^='radCursistGeslacht']:checked").each(function() {
geslachten.push($(this).val());
});
$("[id^='txtCursistGeboortedatum']").each(function() {
geboortedata.push($(this).val());
});
// console.log(voornamen);
// console.log(achternamen);
// console.log(geslachten);
// console.log(geboortedata);
$.post('/wp-content/themes/tweb/processboeking.php',
{
voornamen: voornamen,
geslachten: geslachten,
voornamen: voornamen,
achternamen: achternamen,
geboortedata: geboortedata,
})
.done(function(data)
{
console.log(data)
$('#overzichtboeking').html(data);
}).fail(function(data) {
alert(response.responseText);
});
var li_count = $('.nav-tabs li').length;
var current_active = $('.nav-tabs li.active').index();
if (current_active < li_count) {
$('.nav-tabs li.active').next('li').find('a').attr('data-toggle', 'tab').tab('show');
var txt = $(".oplselect option:selected").text();
var val = $(".oplselect option:selected").val();
$('.showoplnaam').html('Uw selectie: ' + txt);
}
});
console.log data:
Array
(
[voornamen] => Array
(
[0] => G.F.
)
[geslachten] => Array
(
[0] => Dhr.
)
[achternamen] => Array
(
[0] => martens
)
[geboortedata] => Array
(
[0] => 25-10-1993
)
)
<p id="overzichtboeking"></p>
processboeking.php
<?php
include '/home/vhosts/tweb.nl/httpdocs/wp-content/themes/tweb/db/dbcon.php';
print_r($_POST);
?>
<p id="overzichtboeking"></p>
Get complete form data as array and json stringify it.
var formData = JSON.stringify($("#myForm").serializeArray());
You can use it later in ajax. Or if you are not using ajax; put it in hidden textarea and pass to server. If this data is passed as json string via normal form data then you have to decode it using json_decode. You'll then get all data in an array.
$.ajax({
type: "POST",
url: "serverUrl",
data: formData,
success: function(){},
dataType: "json",
contentType : "application/json"
});
Taken from this stackoverflow post: How to send a JSON object using html form data
To go from JSON input on the server side, take a look at this article for converting back to a PHP array: https://www.dyn-web.com/tutorials/php-js/json/decode.php

Jquery get data from JSON (undefined)

When i try to get value from json data i getting undefined
$.get( baseURL + 'vacation/show/' + name_surname, function( data ) {
alert(data); // return [{"id":"1","title":"Testas","start":"2015-03-04","end":"2015-03-04"}]
alert(data.start); // return undefined (should be here 2015-03-04)
});
I need get only start value from data, how can i fix this?
If your data is not an object, you need to make an object out of it to be able to access its values. I am not sure what it is at the moment. Hence, I've put a condition to check the type and then alert accordingly.
$.get( baseURL + 'vacation/show/' + name_surname, function( data ) {
alert(data);
// return [{"id":"1","title":"Testas","start":"2015-03-04","end":"2015-03-04"}]
if (typeof data === "object") {
alert (data[0].start);
} else {
alert (JSON.parse(data)[0].start);
}
});
A demo#fiddle along the same lines.
Use this :
$.get( url, function( data ) {
/* do stuff */
}, 'json');
or this :
$.getJSON( url, function( data ) {
/* do stuff */
});
Before Accessing a Json data from 'data' object, you need to parse it to Json Object.
you can achieve this as below:
var parsedJson=$.parseJSON(data)
Here after you can access the json objects like:
alert(parsedJson[i].start);
where 'i' is the index on N-th data set in the Json object, it can take any numeric value ranging from 0,1,..N
Hope this Helps!!
you can do like following:
$.ajax({
type: 'GET',
url: baseURL + 'vacation/show/' + name_surname,
dataType: 'json',
success: function(data) {
for(var i = 0; i < data.length; i++) {
console.log(data[i].start);
}
},
error: function(e) {
console.log(error);
}
});
Ty to all, it works fine now, just wondering, or i doing good in my next step, if i retrieve from array for loop and then push only dates into array again to get min date, or it will not be a duplication of work?
$.getJSON( baseURL + 'vacation/show/' + name_surname, function( data ) {
if(data != '') {
var dates = [];
for(var i = 0; i < data.length; i++) {
var date = new Date(data[i].start);
dates.push(date);
}
var minDate = new Date(Math.min.apply(null, dates));
var year = minDate.getFullYear();
var month = minDate.getMonth();
$('#calendar').fullCalendar('gotoDate', year, month);
}
});

Jquery Post with JSON Response working

I Have a jQuery Post to a PHP page with generates a JSON Response. It successfully generates JSON because I have it display the whole response. But on the .each I cannot get it to alert. Any Ideas Appreciated. Thank You. The JSON looks like:
[{"Part_Field":"Part_Note:3","Part_Value":"ValueofPart"},{"Part_Field":"Ft_In:3","Part_Value":"12"}, ...
jQuery:
$.post('/scripts/update_detail.php' , field_id + "=" + value, function(data){
var d = document.getElementById("displayjson");
d.innerHTML = data;
$.each( data, function( key, value ) {
alert( value.Part_Field );
});
});
You forgot the string },"json"); in the end.
The corrected code should be:
$.post('/scripts/update_detail.php' , field_id + "=" + value, function(data){
var d = document.getElementById("displayjson");
d.innerHTML = data;
$.each( data, function( key, value ) {
alert( value.Part_Field );
});
},"json"); // Here, you need to tell jQuery that whatever response
// we are getting from server is a JSON string, in your case,
//it was considering it as a string.

Javascript & Ajax - better way to populate objects?

I'm an old 'C' programmer and with Javascript always struggle populating my data following ajax calls; i.e. I always resort to using global references. I'd rather be able to pass in the objects I need to update. Here's one example of what I do now - 'app' is the global (I'd have used a pointer in C :))
treeMapp.login = function ( dialog_div, form_div, server_call ) {
// validate the fields
if ( 0 ) {
}
else {
// send to server & parse JSON response (single line)
var jqxhr =
$.getJSON( server_call,
$( "#" + form_div ).serialize() )
.done( function( data, status ) {
if( status == 'success' ) {
// hack!?
app.user.username = data.username;
app.user.organisation = data.organisation;
app.user.loggedIn = true;
//close the dialog
$( '#' + dialog_div ).dialog('close');
}
else {
// login failed
alert( "login failed!" );
}
})
.fail( function() {
alert( "login: server error" );
}); // end var jqxhr =
} // end else (field validation ok)
}; // end treeMapp.login()
What's the best way of updating passed in parameters?
thanks
mini
You can pass app as an argument to your treeMapp.login function, then within the scope of it it would be local.
treeMapp.login = function ( dialog_div, form_div, server_call, app )
You could assign the data object returned by your jQuery result to app.user, thus avoiding the need for element by element assignment.
i.e. app.user = data
However, normally you ensure the global object can self initialise through a method, or you pass a reference to the global object to the method so it can initialise. Directly using assignment to global variables is (with a few exceptions) poor programming in Javascript as in any other language
UPDATE: the following shows an amalgamation of the answers...
treeMapp.login = function ( dialog_div, form_div, server_call, theapp ) {
var app = theapp; // may be needed for scope issue..
// validate the fields
if ( 0 ) {
}
else {
// send to server & parse JSON response (single line)
var jqxhr =
$.getJSON( server_call,
$( "#" + form_div ).serialize() )
.done( function( data, status ) {
if( status == 'success' ) {
// not a hack
$.extend(this.app.user, data, { loggedIn: true })
//close the dialog
$( '#' + dialog_div ).dialog('close');
}
else {
// login failed
alert( "login failed!" );
}
})
.fail( function() {
alert( "login: server error" );
}); // end var jqxhr =
} // end else (field validation ok)
}; // end treeMapp.login()

Skip duplicate items while rendering page from json

I'm rendering page using ajax and json. Structure of my json is {"status":"ok","rewards":[{"id":201,"points":500},{"id":202,"points":500}]
How do i make ajax loading data only once one if 'points' duplicates in any of hashes?
E.g. i have json with few hashes in which 'points' have same value
Here is my code
$("#page").live('pagecreate', function(e) {
var request = $.ajax({
type: "GET",
url: "example.com/file.json",
dataType: "json",
error: function (data, tex
tStatus){
console.log( status );
console.log( data );},
success: function (data, textStatus){
console.log( "success" );
console.log( status );
console.log( data );
}
})
request.success(function(data, textStatus){
var lis = "";
var seen = {};
$.each(data.rewards, function(key, val){
lis += "<div class = 'reward-ui ui-block-" + String.fromCharCode(97 + key%3) + "'><a href ='#' class ='ui-link-inherit'>" + val.points + "</a></div>";
});
$(".ui-grid-b").html(lis);
});
//$('.even-odd').listview('refresh');
})
});
Add a local array which will store all the items used. Push into this array in $.each function and before doing lis += " " check if the value already exists in the temp array.
Other than that you could try server side sorting before retrieving data ... like suggested above.

Categories