JSON / JQUERY - ajax post, how to process XML data in success function - javascript

Hi I am doing a ajax post via a JSP. I am posting JSON data in string format (parsed using parseJSON, then I use the JSON stringify to return to a string.
This post works fine. But what I am not sure how to do, is basiclally I sending this to a a client gateway, which translates this jsonString into XML to do some internal processing. This internal work will generate an XML response, that needs to be sent back to my JSP. I plan on receiving and this XML in the ajax post 'success' function facility.
So far I have been able to make this work with the success function "data" item being HTML. But I am not sure how this can be done when I want to XML. How do I do this? How do I receive XML, and how do you host/find/display the XML for it to be returned in the sucess 'data' function?
My other option, is that if it is not XML that I want to recieve, I could possibliy receive JSON data. How can I host/find/display JSON data for it to be returned in the sucess 'data' function?
This is my post code:
$.ajax({
type: "POST",
url: suppliedURL,
data: "jsonData=" + jsonString, // I have already done a json stringify on this.
success: function(data, textStatus, jqXHR) {
alert('Success : ' + data); .. I want this to be XML
alert('textStatus : ' + textStatus);
alert('jqXHR : ' + jqXHR);
var jsonJqXHR = JSON.stringify(jqXHR);
alert('jsonJqXHR : ' + jsonJqXHR);
},
error:function (xhr, ajaxOptions, thrownError){
alert('Error xhr : ' + xhr.status);
alert('Error thrown error: ' + thrownError);
},
//complete: alert('complete'),
dataType: "text" // xml, json, script, text, html
});

Change dataType to xml; after that data in the success method will be an XML document.

Related

jQuery AJAX does not detect success

I have the following code.
$(".likeBack").on("click", function(){
var user = $(this).attr("user");
var theLikeBack = $(this).closest(".name-area").find(".theLikeBack");
$.ajax({
type: "POST",
dataType: "json",
url: "processes/rewind-knock.php",
data: "user="+user+"&type=likeback",
success: function(json){
alert("SUCCESS");
},
error: function(jqXHR, textStatus, errorThrown){
alert("XHR: " + jqXHR + " | Text Status: " + textStatus + " | Error Thrown: " + errorThrown);
}
});
});
Here, everything is functional. Network tab shows request and response well received as required. However, the success part is not getting executed. I tried adding beforeSend and complete and both are getting executed but success part (nothing inside the success blog is getting executed). I don't understand the reason why.
UPDATE
Add error part. It returns:
XHR: [object Object] | Text Status: parsererror | Error Thrown: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
UPDATE 2
Screenshot
give data in ajax like this and check,
data : {'user':user,'type':'likeback'},
In your Php code when you return the data, place all data in a array then use this,
echo json_encode($arr); //return the array in json form
now in your success function use
console.log(JSON.parse(json));
hope may help you. Thank you

AJAX Post Error - SyntaxError: Unexpected token R in JSON at position 5

I am trying to send the following JSON file to an AJAX POST method.
See AJAX method below:-
$(document).on('submit', '#create-recipe-form', function(){
// get form data
var form_data= {
"recipe_name":"ghjghjh",
"category_name":"Desert",
"category_id":"8",
"Apple":"Apple",
"Carrots":"Carrots",
"step1":"ghj",
"step2":"",
"step3":"",
"step4":"",
"prep":"6"
};
// submit form data to api
$.ajax({
url: "http://localhost:8082/recipe_app/api/recipes/create_recipe.php",
type : "POST",
//contentType : 'application/json',
contentType : 'json',
data : form_data,
success : function(result) {
createRecipeIngredientsForm();
// recipe was created, go back to recipes list
//showRecipes();
},
error: function(xhr, resp, text) {
// show error to console
console.log(xhr, resp, text);
}
});
The above AJAX method actually correctly calls the .php file and the data is inserted into the database. But there is an error returned and therefore the 'success' section never runs. This is so frustrating, can anybody shed any light?
SyntaxError: Unexpected token R in JSON at position 5
at parse ()
at ajaxConvert (http://localhost:8082/recipe_app/app/assets/js/jquery-3.2.1.js:8754:19)
at done (http://localhost:8082/recipe_app/app/assets/js/jquery-3.2.1.js:9222:15)
at XMLHttpRequest. (http://localhost:8082/recipe_app/app/assets/js/jquery-3.2.1.js:9514:9)
replace this line of your ajax
form_data=JSON.stringify($(this).serializeObject());
to
form_data=$(this).serializeObject();

Send an array from node server to js script

My server (node.js) maintains an array :
var list = [];
I want to use this array in some js code (client side). I would like to retrieve it thanks to ajax. What is the best practice?
$.ajax({
url: "http://localhost:8000/updatePendingAlerts",
timeout: 2000,
success: function (data) {
console.log(data);
//data should be an array
},
error: function(jqXHR, textStatus, errorThrown) {
clearInterval(timeout);
alert('error ' + textStatus + " " + errorThrown);
}
});
Serialise it to JSON (with JSON.stringify) and output it with an application/json content-type header.
It will then be an array in data with the client side JavaScript you already have.

ajax call can't pass parameters and work only with some browser

I have problem with this this function that should make an ajax call:
function updateCountriesPrice(){
var countryFrom = select_country_from.options[select_country_from.selectedIndex].value;
var countriesTo = JSON.parse("[" + $('#countriesToUpdate').val() + "]");
var arrayProductCode = [];
arrayProductCode=localStorage.list_id.replace(/ /g,'');
var data = {'products_list': arrayProductCode,
'country_from': countryFrom,
'countries_to': countriesTo};
console.log(data);
$.ajax({
url: './products_actions_prices', //Server script to process data
type: 'POST',
xhr: function() { // Custom XMLHttpRequest
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){ // Check if upload property exists
myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // For handling the progress of the upload
}
return myXhr;
},
//Ajax events
success: function(data, textStatus, jqXHR){
$('#div_action_selected').html('').hide();
jQuery('#wrapper').append('<div class="flash success" >'+jqXHR.responseJSON.text+'</div>');
setTimeout(function(){$('.flash').slideUp(1000);},3000);
$('#div_action_selected').html('').hide();
jQuery.each(jQuery('.check_box'),function(key,value){
if(jQuery('#select_all').is(':checked')){
$(this).prop('checked', false);
}
});
$('#select_all').prop('checked', false);//$('#select_actions').hide();
$('#select_all_products_div').hide();
localStorage.clear();localStorage.setItem('list_id','');
setInterval(location.reload(),2500);
hideDivAction();
},
error: function (jqXHR, textStatus, errorThrown){
$('#div_action_selected').html('<div id=\"errorExplanation\" class=\"errorExplanation\" data-hook=\"\">'
+' <h2>One error prohibited this action:</h2>'
+' <p>There were problems with the call.</p>'
+' </div>');
setTimeout(function(){$('#div_action_selected').slideUp(1000);},3000);
//$('#select_actions').attr('value','');
},
// Form data
data: data,
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
contentType: false,
processData: false
});
}
Using chrome the call work and i see the success result, but my params variable doesn't contains the data that i pass with ajax.
When I call
console.log(data);
I can see the datas exactly as i want them but they doesn't arrive to my rails controller.
Using firefox the ajax either start.
Thanks.
You are missing dataType.
According to jQuery,
dataType (default: Intelligent Guess (xml, json, script, or html))
Type: String
The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). The available types (and the result passed as the first argument to your success callback) are:

How to post json array to PHP using jQuery's ajax method?

I have a json array created by javascript and need to post it to a php file in order to save the data into the database.
var myArray = [{
"picture":"picture1.jpg",
"picture_comment":"some comment about picture1",
"pictureid":16,
"u0id":80,
"u1id":82,
"u2id":78,
"u3id":79,
"u4id":81,
"param0": "60f3f",
"param1":"48dd2",
"param2":"4f2f7",
"param3":"8d101",
"param4":"5efcc",
"active":false,
"dutyid":1256,
"t":0
},
{
"picture":"picture2.jpg",
"picture_comment":"some comment about picture2",
"pictureid":160,
"u0id":18,
"u1id":48,
"u2id":70,
"u3id":95,
"u4id":74,
"param0": "1123f",
"param1":"48d13",
"param2":"595f7",
"param3":"78ad8",
"param4":"4efdc",
"active":false,
"dutyid":125,
"t":4
}
//goes like this about more than 20 times.
;
I have tried to post it using jQuery.ajax but I was not successful.
$.ajax({
type: "POST",
url: "goDoMyWork.php",
data: myArray,
dataType: "json",
success: function(){
alert("Done! You'll be redirecting now.");
window.location.href = "/index.php";
}
,
error: function(jqXHR, textStatus, errorThrown)
{
alert("Fail!");
}
});
I have to insert some of the data into one table and some of them into another table.
I have got the following error using:
alert(jqXHR + '-' + textStatus + '-' + errorThrown);
[object Object]-parsererror-SyntaxError: JSON.parse: unexpected character
Try changing data: myArray to data: {mydata : myArray}. Passing your array directly causes jQuery to pass it in an odd format. http://api.jquery.com/jQuery.param/
JSON.parse is the function that transforms text in json-format into a JavaScript object. What you seem to be wanting to do is throw some data at the server, where the server will handle it further.
What you are actually doing is setting the dataType to json. In the documentation you can read that this is the data-type you are expecting to get back from the server. jQuery will therefor throw the data it gets back from the server through JSON.parse, but apparently the data is not a well-formed json-string. Removing the dataType from your request will fix this, as the data will most likely not be parsed. Therefor, whatever gets returned will be in the form of a string.

Categories