How to send array in AJAX using JSON - javascript

I am fairly new to JS and AJAX, and for some reason I can not send my dynamically generated and read data via AJAX. How do I properly send an array via AJAX to PHP script?
I have tried following the instructions but I can not get the AJAX to send the data. The first try was a complete bust, the second gets error:
Uncaught TypeError: Illegal invocation
but it seems to originate from the JS-library instead of my code (though the code is most probably the reason for it!) and I do not know what to do with it.
//first thing I tried
var i = 1, j = 0, cu = [], cu2 = [];
while (i <= tilit ) {
cu[j] = document.getElementById("til_nro_"+i);
console.log(cu[j].value);
i++;
}
var dynamic_account_value = JSON.stringify(cu);
jQuery.ajax({
type: "POST",
url: 'http:mysite.php',
dataType: 'json',
data: { dynamic_account_count:tilit, db:cu , id:id, result:dynamic_account_value
}
});
//2nd thing I tried
var i = 1, j = 0, cu = [], cu2 = [];
while (i <= tilit ) {
cu[j] = document.getElementById("til_nro_"+i);
cu2.push(JSON.parse(cu[j].value));
i++;
}
var tilinrot_lisa = JSON.stringify(cu2);
jQuery.ajax({
type: "POST",
url: 'http:mysite.php',
dataType: 'json',
data: { dynamic_account_count:tilit, db:cu , id:id, result:tilinrot_lisa
}
});

First, give them something that makes selection easier, like a common class. Second, use jquery serialize
$.ajax({
url : "foo",
data : $(".bar").serialize(),
success : function(response) {}
})

Try this code snippet, Try to send just one variable then go for another & use content type.
u can use //console.log(JSON.stringify(cu)); to view what's inside.
jQuery.ajax({
type: 'post',
dataType: 'json',
data: {your_var:JSON.stringify(cu)},
contentType: "application/json"
});

Related

Get Object XmlDocument value

I'm executing an ajax call to a external api (this cannot be modified) to upload an store a file into a folder. This request must return a path (ex. "C:\Doctos\File.pdf" but after a console.log is returning something like this:
#document < string xmlns="http://tempuri.org/">"C:\Doctos\File.pdf"
So my question is, what can I do to get only the text that I want without any change in the api (because I'm not able to do it).
Here is the ajax call that I'm using.
PD. This ajax call is using the provided structure for the dev team that developed the api so things like dataType also cannot be modified
var data = new FormData();
var files = $('#fileUpload').get(0).files;
if (files.length > 0) {
data.append("UploadedFile", files[0]);
}
$.ajax({
type: 'POST',
url: 'api/v1/moreurl/UploadFile',
contentType: false,
processData: false,
data: data,
success: function (data) {
var res = data;
//Returns above example
console.log(res);
//Returns something like <p>[object XMLDocument]</p>
$('#MyInput').attr('src', res);
}
});
I would use regular expressions to get the desired string from received data. Put this after success line.
var regex = />\"(.*)\"/;
var matched = regex.exec(data);
var result = matched[1];
console.log(result);
The regex matches the last quoted string in your example.
You can get the data in the xml with jQuery
$.ajax({
type: 'POST',
url: 'api/v1/moreurl/UploadFile',
contentType: false,
processData: false,
data: data,
success: function (data) {
// Get the contents of the xml
var file = $(data).find('string').text();
$('#MyInput').attr('src', file);
}
});

Push/Add multiple JSON objects one by one to the API using ajax and for loop

I'm working on a code where I can push a JSON objects one by one inside an array going to the API using AJAX and for loop. The code here is just a rough sample of what I have been working on. I can't seem to make it work on in pushing the objects to the API JSON array
var lms_json = <?php echo json_encode($json_data); ?>;
var jobjects = JSON.parse(lms_json);
var data = jobjects[0];
for ( i = 0; i < jobjects.length; i++ ) {
var data = jobjects[i];
$.ajax({
type : 'POST',
url : url,
data : data,
dataType : 'json',
success : function() {
console.log(success);
},
error : function(error) {
console.log('Error')
}
})
}
You need to use JSON.stringify to serialize your JSON object. Also, specify the content-type to make the server expect JSON data. This might work:
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(data),
contentType: "application/json",
complete: callback
});
I think that your problem is that AJAX is asynchronous process so you can do the following to do it correctly:
var lms_json = <?php echo json_encode($json_data); ?>;
var jobjects = JSON.parse(lms_json);
var i=0;
function makeAjax(url, objs){
var data = objs[i];
i++;
$.ajax({
type : 'POST',
url : url,
data : data,
dataType : 'json',
success : function() {
console.log(success);
makeAjax();
},
error : function(error) {
console.log('Error')
}
})
}
makeAjax(url,jobjects);
So After every success callback run it will run the next. so it will be synchronous process.
I hope it helps.

json couldn't change the dataWithLabels

Please can you help see the code. I would like to change the title name from 'Jason' to the temperature written in the JSON file.
var dataWithLabels = [
{
"title":"Jason",
}];
$.ajax({
url: "http://api.wunderground.com/api/2b38dcff93aa3dff/conditions/q/CA/Santa_Clara.json",
type: "GET",
dataType: "json",
success: function(data) {
for(var i=0;i<1/*dataWithLabels.length*/;i++){
var statistic = data.current_observation;
dataWithLabels[i]['title']= statistic.temp_c;}}
//wanted to change Jason to the temperature written at the JSON file.Please help.
});
alert(dataWithLabels[0]['title']);
http://codepen.io/wtang2/pen/bEGQKP
It's NOT a duplicate, I am trying to replace the result from JSON file to title of dataWithLabels object
Since I don't know, if your JSON you are requesting is correct, I just assume it is. Still, if you like to see, what is happening in dataWithLabels after your Ajax-Request, you need to rewrite the function a little:
var dataWithLabels = [{
"title": "Jason",
}];
$.ajax({
url: "http://api.wunderground.com/api/2b38dcff93aa3dff/conditions/q/CA/Santa_Clara.json",
type: "GET",
dataType: "json",
success: function(data) {
for (var i = 0; i < 1 /*dataWithLabels.length*/ ; i++) {
var statistic = data.current_observation;
dataWithLabels[i]['title'] = statistic.temp_c;
alert(dataWithLabels[i]['title']);
}
}
//wanted to change Jason to the temperature written at the JSON file.Please help.
});
Now, the status of dataWithLabels is alerted AFTER you insert the statistic.temp_c. Your code always alerts the state BEFORE the Ajax-request.
Hope that helps!
This is because AJAX request works asynchronously so you need to alert the result only after the AJAX request is completed for that you can do
var dataWithLabels = [{
"title": "Jason",
}];
$.ajax({
url: "http://api.wunderground.com/api/2b38dcff93aa3dff/conditions/q/CA/Santa_Clara.json",
type: "GET",
dataType: "json",
success: function(data) {
for (var i = 0; i < 1 /*dataWithLabels.length*/ ; i++) {
var statistic = data.current_observation;
dataWithLabels[i]['title'] = statistic.temp_c;
alert(dataWithLabels[i]['title']); // Alert only after data is received
}
}
});

jquery ajax call "metho" instead of "method"?

I have a script.js that uses jQuery's ajax function to query string to a php file, it works as expected BUT i find it odd that i must use the "metho" sintax instead of the "method", look at this,
this works
script.js
$.ajax({
url: 'php/printers.php',
metho: 'POST',
data: {
data: c,
orderby: d,
},
success: function(output) {
$('.results').html(output);
var tbody = document.getElementsByClassName('results');
var rows = tbody[0].getElementsByTagName('tr');
ajax.applyClass(rows);
}
});
this doesn't
$.ajax({
url: 'php/printers.php',
method: 'POST',
data: {
data: c,
orderby: d,
},
success: function(output) {
$('.results').html(output);
var tbody = document.getElementsByClassName('results');
var rows = tbody[0].getElementsByTagName('tr');
ajax.applyClass(rows);
}
});
i'm preplexed that i must use the "metho" instead "method" :O i don't even know how that happened, though it was a typo??
The difference is that the default method of ajax is "GET". Since there's no metho option for ajax, that's ignored and the default is being used. When you specify method: "POST", you're overriding the default, using POST instead of GET.
So we can infer that the script being called works correctly when GET is used, and not when POST is used (probably because of where it looks for the data it receives).

jQuery .ajax Call Returns JSON ParseError Even Thought JSON Appears to be Correct?

I'm getting a ParseError even though my JSON validates on jsonlint.com.
Here is the jQuery code:
$.ajax({
url: path,
type: 'GET',
data: {},
cache: false,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
var a = 'breakpoint here doesn't activate';
},
error: function (x, y, z) {
var b = 'code execution stops at a breakpoint here.';
}
});
Here is the PHP code that is being called:
function getAllAnswersToHitViaAjax($theJobName) {
$testData[0] = 'testing123';
$encodedData = json_encode($testData);
echo $encodedData;
return;
}
This comes back to a breakpoint set in the error: function of my .ajax call. Parameter Y is set to "parseerror", and x.responseText =
["testing123"]
I've been looking into this for hours so far. I've looked at many relevant StackOverflow posts, but none have solutions that work in this case.
How can I get a success response from this .ajax call?
Thanks very much in advance to all for any info.
There's nothing visibly wrong with your code, and it works fine when I try it on my local machine. However, your comment above is a big clue:
I just looked at the z param in the Safari console, and found this:"undefined is not a function (evaluating 'JSON.parse(a+"")')" How could that be happening?
It could happen if some code somewhere uses "JSON" as a global variable name, hiding the built-in window.JSON object.
Check for Notice or Warning in your php code, if their is any then remove that and then try. Hop this will help you.
JavaScript allows either single or double quotes for strings, but JSON only allows double quotes. See http://www.json.org/
See also jQuery.parseJSON single quote vs double quote
Just Use
function getAllAnswersToHitViaAjax($theJobName) {
$testData[0] = 'testing123';
echo json_encode($testData);
}
Then in your AJAX you can do
$.ajax({
url: path,
type: 'GET',
dataType: 'json'
success: function(data){
for (var i = 0; i < data.length; i++) {
//DO YOUR STUFF
}
}
});
Please use
$.ajax({
url: path,
type: 'GET',
cache: false,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
var a = 'breakpoint here doesn\'t activate';
},
error: function (x, y, z) {
var b = 'code execution stops at a breakpoint here.';
}
});
and in your PHP CODE Paste this code.
function getAllAnswersToHitViaAjax($theJobName) {
$testData[0] = 'testing123';
$encodedData = $testData;
echo json_encode($encodedData);
exit;
}
May be after digging more in your code I assume that in your PHP code you were not passing data properly. Please use exit or die method to pass data back to ajax. Please check.
Try with the below code,
function getAllAnswersToHitViaAjax($theJobName) {
$testData[0] = 'testing123';
echo json_encode($testData);
die();
}
$.ajax({
url: path,
type: 'GET',
dataType: 'json'
success: function(data){
console.log(data);
var result = JSON.parse(data);
console.log(result);
}
});

Categories