Access to object after ajax function - javascript

I have this ajax jquery code:
$("#serial_number").submit(function(e) {
var url = "/getVoucher"; // the script where you handle the form input.
$.ajax({
type: "GET",
url: url,
data: $("#serial_number").serialize(),
dataType: "json",
success: function(data)
{
console.log(data);
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
and I get this fron console.log:
How I can access to object Code element?
I try with: data.Code also try data.Description but browser give me error... How to access inside success function in ajax code?

When you console.log a variable, the output in the console are it's contents, so if you are still seeing:
Object{ data: Object }
That means that the variable data has a key data inside of it. Try:
console.log( data.data.Code );
To access the object's contents.

Related

A part of AJAX response storing in PHP variable

I need to store a piece of data, into PHP variable, which is received through AJAX response in an input box. How can I do this?
<script type="text/javascript">
$(document).ready(function() {
$("#user_id").change(function() {
var id = $(this).val();
var dataString = 'user_id='+ id;
$.ajax({
type: "POST",
url: "wmat_details.php",
data: dataString,
cache: false,
success: function(result) {
var data = result.split(",");
$('#name').val(data[0]);
$('#email').val(data[1]);
$('#ref_id').val(data[2]);
$('#candidature_start').val(data[3]);
$('#candidature_end').val(data[4]);
$('#default_attempts').val(data[5]);
$('#existing_complimentary').val(data[6]);
$('#wmat_start').val(data[9]);
$('#wmat_end').val(data[10]);
$('#attempts_taken').val(data[11]);
}
});
});
});
</script>
As shown in above code, I want to store $('#attempts_taken').val(data[11]); this value to a PHP variable. Any insight is appreciated.
Unfortunately you can't.
PHP is server side while jQuery (JS) is client side. They are two separate layers of abstraction that interact only when the client call the server.
I don't have enough informations about what you need to do with data[11] but it seems that you have only one option: make a consecutive AJAX call to the php file that will manipulate data[11].
The consecutive AJAX call must be executed from inside the first call success callback; something like this:
success: function(result){
// Your on success logic
// ...
// Prepare the object to send to the server
var objData = {};
objData.attemptsTaken = data[11];
// Execute the second AJAX call to the server
$.ajax({
type: "POST",
url: "second_call_destination_file.php",
data: objData,
success: function(result){
// Do something on success
},
error: function(){
// Do something on error
},
complete: function(){
// Do something on complete (executed after success and error)
}
}
You cannot store ajax response into a php variable.
way 1 :
You can make another ajax call.
way 2 :
you can set session.

How to loop each JSON value after is retrieving its data through AJAX

var buttonOptions = {
gmap: map,
name: 'Download JSON File',
position: google.maps.ControlPosition.TOP_RIGHT,
action: function () {
$.ajax({
type:"GET",
contentType: "application/json; charset=utf-8",
url: "getJSON.php",
data: "{}",
//dataType: 'json',
cache:false,
success: function(data){
}
});
}
}
I have a button that returns the JSON file below
[{"marker_title":"Santa Venera","marker_description":"Hometown","longitude":"","latitude":"","icon":"undefined"},{"marker_title":"Hamrun","marker_description":"Street","longitude":"0.1709747314453125","latitude":"51.44395066709662","icon":"https:\/\/maps.gstatic.com\/mapfiles\/ms2\/micons\/tree.png"},{"marker_title":"PlaceA","marker_description":"PlaceA","longitude":"0.292510986328125","latitude":"51.40884344813292","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/info-i_maps.png"},{"marker_title":"PlaceB","marker_description":"PlaceB","longitude":"0.232086181640625","latitude":"51.434106241971826","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/info-i_maps.png"},{"marker_title":"PlaceC","marker_description":"PlaceC","longitude":"0.07656097412109375","latitude":"51.43325010472878","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/info-i_maps.png"},{"marker_title":"Home","marker_description":"Town","longitude":"0.1764678955078125","latitude":"51.43753063050015","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/library_maps.png"},{"marker_title":"PLACED","marker_description":"PLACED","longitude":"0.26641845703125","latitude":"51.41783689062198","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/parking_lot_maps.png"},{"marker_title":"FF","marker_description":"EEE","longitude":"0.2053070068359375","latitude":"51.426828563976954","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/parking_lot_maps.png"},{"marker_title":"Qormi","marker_description":"Road","longitude":"14.471054077148438","latitude":"35.875419840918845","icon":"https:\/\/maps.gstatic.com\/mapfiles\/ms2\/micons\/tree.png"}]
My question is, how am I going to loop and display each field in the Success function? I tried using $.each to no avail. Also how can I count each value. I used $('#msg').html(data.length);, however it is counting each character in the JSON file, instead of the actual value. Thanks.
I used $('#msg').html(data.lenght);, but it is counting each character in the JSON file, instead of the actual value.
It's quite evident because you haven't parsed the JSON yet, so data is evaluated as a string here.
Solution:
You need to parse the JSON data before trying to access it. So your code need to be like this:
success: function(data){
data = JSON.parse(data);
$('#msg').html(data.length);
}
how am I going to loop and display each field in the Success function?
And then you can loop over dataafter it's parsed with .each():
success: function(data){
data = JSON.parse(data);
$('#msg').html(data.length);
data.each(function(){
//Your code here
});
}
Edit:
Another thing in your Ajax call why are you using url: "getJSON.php"? In that case the Ajax call will just load the content of the PHP file as a string.
In the URL you should put your .json file or a web service that returns a JSON string.
Demo:
Here's a Demo snippet showing the problem in details and where did 1610 came from in data.length :
var json = '[{"marker_title":"Santa Venera","marker_description":"Hometown","longitude":"","latitude":"","icon":"undefined"},{"marker_title":"Hamrun","marker_description":"Street","longitude":"0.1709747314453125","latitude":"51.44395066709662","icon":"https:\/\/maps.gstatic.com\/mapfiles\/ms2\/micons\/tree.png"},{"marker_title":"PlaceA","marker_description":"PlaceA","longitude":"0.292510986328125","latitude":"51.40884344813292","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/info-i_maps.png"},{"marker_title":"PlaceB","marker_description":"PlaceB","longitude":"0.232086181640625","latitude":"51.434106241971826","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/info-i_maps.png"},{"marker_title":"PlaceC","marker_description":"PlaceC","longitude":"0.07656097412109375","latitude":"51.43325010472878","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/info-i_maps.png"},{"marker_title":"Home","marker_description":"Town","longitude":"0.1764678955078125","latitude":"51.43753063050015","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/library_maps.png"},{"marker_title":"PLACED","marker_description":"PLACED","longitude":"0.26641845703125","latitude":"51.41783689062198","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/parking_lot_maps.png"},{"marker_title":"FF","marker_description":"EEE","longitude":"0.2053070068359375","latitude":"51.426828563976954","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/parking_lot_maps.png"},{"marker_title":"Qormi","marker_description":"Road","longitude":"14.471054077148438","latitude":"35.875419840918845","icon":"https:\/\/maps.gstatic.com\/mapfiles\/ms2\/micons\/tree.png"}]';
//logging json.length without parsing it
console.log('logging json.length without parsing it');
console.log(json.length);
var data = JSON.parse(json);
//logging data.length after parsing it
console.log('logging data.length after parsing it');
console.log(data.length);
As #chsdk said data is returned being as a string instead of a Javascript object you may want to take a look at $.getJSON() instead of $.ajax() for iterating over JSON objects
$.getJSON( "getJSON.php", function( data ) {
var count = data.length;
$.each( data, function( key, val ) {
//perform operations on data
});
});
http://api.jquery.com/jquery.getjson/

How do I convert this Ajax function (in prototype) to a jquery one?

Can anyone please help me to translate this function in prototype to the equivalent in jQuery
function updateNewsletter(){
if ($('newsletter_dump')){
$('newsletter_dump').remove();
}
newsletterParam = $('newsletter_form').serialize(true);
newsletterParam.template_output = 'box/plugin_newsletter';
new Ajax.Updater('newsletter_form_holder', 'index.php', {
parameters: newsletterParam,
evalScripts: true
});
}
Thanks is advance.
I tried this code but not working. I keep getting an object error
function updateNewsletter(){
if ($('#newsletter_dump')){
$('#newsletter_dump').remove();
}
newsletterParam = $('#newsletter_form').serialize(true);
newsletterParam.template_output = 'box/plugin_newsletter';
$.ajax({
type: 'GET',
url: 'index.php',
data: {"newsletterParam" : "newsletter_form_holder"},
dataType: 'script',
success: function(data){
alert(data);
},
error: function(e){
alert(e);
}
});
}
The problem may come from newsletterParam.template_output = 'box/plugin_newsletter'; Any idea on how to add another form element to the serialised one in jQuery?
Thanks
Unlike Prototype's serialize function, jQuery's serialize function returns a string only. Your error is due to the fact that you are using newsletterParam as an object rather than a string. So to fix the problem just append the template_output parameter as a string:
newsletterParam = $('newsletter_form').serialize();
newsletterParam += '&template_output=box/plugin_newsletter';
Also, the data setting in your ajax call should be
data: newsletterParam,

AJAX form submission hits proper endpoint but doesn't pass variables

I'm working on the review page before a user buys a product, and on the page is a small field for discount codes, which I want to pass to an endpoint via ajax. I'm using the following javascript function, and the submission happens and returns (even hits the intended endpoint) - but no data gets passed through (verified in logs).
Any idea why no params would be getting passed through?
<script>
$("#discount_code_submit").click(function() {
var url = "/confirm_discount"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#discount_form").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response
if(data != "false")
{
console.log(data);
}
}
});
return false; // avoid to execute the actual submit of the form.
});
</script>
This is because jQuery's serialize method creates a String representation of the form data, in the traditional url query string format. (Please see here: http://api.jquery.com/serialize/)
E.g., calling serialize can return a string such as:
'?query=help&numResults=200'
On the other hand, jQuery's ajax method expects the form data to be provided as an object literal. (Please see here: http://api.jquery.com/jQuery.ajax/)
E.g.
{
query: 'help',
numResults: 200
}
So you can change your ajax call to look like:
$.ajax({
type: "POST",
url: url,
data: {
param1: 'somevalue',
param2: 200
},
success: function(data)
{
alert(data); // show response
if(data != "false")
{
console.log(data);
}
}
});
Or, you could also construct your object literal from the form using a custom function and then provide the reference in the ajax call.
$.ajax({
type: "POST",
url: url,
data: myPreparedObjectLiteral,
success: function(data)
{
alert(data); // show response
if(data != "false")
{
console.log(data);
}
}
});
You could also use http://api.jquery.com/serializeArray/ since it does pretty much what you'll need to convert a form to the json literal representation.
Finally, for a good discussion on converting forms to json objects for posting, you can see the responses here on an SO question: Convert form data to JavaScript object with jQuery

Issue in getting a property in a JSON file using jQuery GET

I ma using jQuery get to retrieve a simple property on a JSON file.
With the following script I get undefined.
What am I doing wrong here?
<script>
$(document).ready(function() {
var urlOriginal = 'http://xxx.com/xxx/xxx/xxx/resources.js';
var urlResource = 'proxy_dr3.php?proxy_url=' + encodeURIComponent(urlOriginal);
$.get(urlResource, function(data) {
console.log(data); // I can see all the content from the JSON FILE
console.log(data.urlPage); // undefined - PROBLEM HERE
var urlHTML = data.urlPage;
/*$.get(urlHTML, function(data) {
$('#result').html(data);
});*/
});
});
</script>
content for resource.js is json
{
"urlPage": "http://xxx.com/xxx/xxx/xxx/article_517d960f0cf2fe38916a2f9d.html"
}
The result type in Network is text/html. After loading resource.js
$.get won't guess it's JSON as the mime type your server gives is wrong.
You could parse the provided value (which is probably a string) using JSON.parse but you should use $.getJSON, so that the callback receives a parsed value.
$.getJSON(urlResource, function(data) {
console.log(data);
console.log(data.urlPage);
});
you can use any one method which is best suitable for your app.
$.ajax({
type: "GET",
data: "ur data",
url: "ur url",
contentType: "application/json; charset=utf-8",
success: function(data) {
}
});
or you can use $.getJSON function

Categories