Post multiple jquery with ajax to python - javascript

my question: I'm trying to post multiple data using ajax request. But I don't get anything back from python script. I get a error from console, it says:
data: { serializedData1, serializedData }
error: Uncaught SyntaxError: Unexpected token ,
But if I remove the , I will get more and more errors syntax errors.
If I edit the javascript like this: data: serializedData1 it wil work but it isn't what I want.
var valueID = $(this).parent().parent().find(".inputLiveID")// this is the id I want
var serializedData1 = valueID.serialize()
var $form = $(this); // I want this value too
var serializedData = $form.serialize();
request = $.ajax({
url: "/accounts/editnad/",
type: "post",
data: { serializedData1, serializedData }
});
request.done(function (response, textStatus, jqXHR){
console.log(response)
});
request.fail(function (jqXHR, textStatus, errorThrown){
console.error(
"The following error occured: "+
textStatus, errorThrown
);
});
python script:
def editnad(updatenad):
result = False
updid = updatenad.POST.get("newid")
newnr = updatenad.POST.get("nadcodenr")
newbesch = updatenad.POST.get("nadbeschikbaar")
return HttpResponse(updid,newnr)

You need to pass name/value pairs in your ajax call, for example
$.ajax({
url: 'myScript.py',
data: {form1: serializedData1, form2: serializedData},
success: function(response) {
//do something with response
}
});
Then in the python
updid = udatenad.POST.get('form1').updid
You'll also note I didn't assign the ajax call to a variable, I used a success callback instead. If you want to use a promise you can assign it, and then use resolution/broken callbacks. Guess I'm old school.

You define an array in JS with [], not {}.
data: [ serializedData1, serializedData ]

Related

Ajax error getting called instead of success

<script>
function editComment(id) {
var content = $('#Content').val();
var modelData = { 'Id': id, 'Content': content };
$.ajax({
type: 'POST',
dataType: 'json',
url: '#Url.Action("EditC", "Comment")',
data: JSON.stringify({ model: modelData }),
contentType: 'application/json',
success: function () {
alert("YES");
},
error: function () {
alert("Error");
}
});
}
</script>
Here the server is returning 200 OK, but for some reason the error function is getting called. Both type and contentType seem to be correct. Any idea how to fix this?
Edit:
After adding
error: function (xhr, textStatus, error) {
console.log(xhr.responseText);
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
this is what is being logged:
parsererror
parsererror
SyntaxError: Unexpected end of JSON input
at parse (<anonymous>)
at ajaxConvert (jquery-3.4.1.js:9013:19)
at done (jquery-3.4.1.js:9483:15)
at XMLHttpRequest.<anonymous> (jquery-3.4.1.js:9785:9)
Moving to an answer for future readers...
The server is indeed returning a successful response, but an empty successful response:
return new HttpStatusCodeResult(200);
However, the client-side code is expecting valid JSON:
dataType: 'json',
As a result, after the successful response is received, internally the jQuery code attempts to parse that response as JSON and that fails, resulting in triggering the error callback.
Since there's no response body (and in most cases even when there is, as long as the server returns the correct MIME type), you don't need or want to specify a dataType in the jQuery AJAX operation. Simply remove this part:
dataType: 'json',

Unable to post data on Jquery ajax

My code to post data to server is like this
$('#btn').click(function () {
var myarray = [];
$("#DocumentList input[type=checkbox]:checked").each(function () {
myarray.push($(this).attr('uniqueid'));
});
alert(myarray);
$.ajax({
url: "url",
type: "post",
dataType: "text",
data: myarray,
success: function (response) {
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
});
on alert I am getting the data I want to post to server, But when I inspect the call on Chrome,I can see that data is not getting posted (screenshot added below). What can be the reason for this behavior?
jQuery does not expect you to pass an array of strings to data.
It can't process that usefully.
Typically you would pass an object of name: value pairs:
data: { something: myarray }
… which will URL encode it with the something[] extended syntax introduced by PHP.
You will need to make sure the encoding you send matches whatever the server expects though.

Access post data from inside ajax error function

I have the below javascript function that takes POST data and sends post request to server using Ajax
function postData(post_data) {
console.log(post_data, "----------->");
var data = post_data;
var url = "/super/man/"
$.ajax(
{
type: "POST",
url: url,
data: post_data,
dataTpe: "json",
success: function (data) {
debugger;
},
error: function (jqXHR, textStatus, errorThrown) {
debugger;
// Can we access the post_data inside this error function ?
},
}
);
};
So what my actual point is, because of some reason the server is sending a 500 response and so the execution point is coming to error: function (jqXHR, textStatus, errorThrown, data), here I want to access post_data to display something to the user.... So can we access the post_data inside ajax error function above?
In case someone looks for a generic way to do this, here is how i did it: In case your handler functions are defined where their scope don't allow you to access some variables, you can add them to the ajax object itself in the function beforeSend. You can then retreive it in the ajax object by using this.
$.ajax({
url:'/dummyUrl',
beforeSend: function(jqXHR, plainObject){
plainObject.originalUrl = 'myValue';
},
success: function (response) {
$('#output').html(response.responseText);
},
error: function () {
$('#output').html('Bummer: there was an error!');
$('#myValue').html(this.originalUrl);
},
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="output">waiting result</div>
<div id="myValue"></div>
function postData(post_data) {
console.log(post_data, "----------->");
// var data = post_data; // why ?
var url = "/super/man/"
$.ajax(
{
type: "POST",
url: url,
data: post_data,
dataTpe: "json",
success: function (response) { // pay attention to args and vars naming as it makes the code easier to read
// use response
},
error: function (jqXHR, textStatus, errorThrown, data) {
// handle error
console.log(post_data); // and the magic happens
},
}
);
};
Above this issue you were having wrong key "dataType" i have modified it. Secondly, "post_data" is in your scope you can access it without any issue.
function postData(post_data) {
console.log(post_data, "----------->");
// var data = post_data; // why ?
var url = "/super/man/"
$.ajax(
{
type: "POST",
url: url,
data: post_data,
dataType: "json",
success: function (response) { // pay attention to args and vars naming as it makes the code easier to read
// use response
},
error: function ( jqXHR jqXHR, textStatus, errorThrown) {
// post data is in your scope you can easily access it
console.log(post_data); // and the magic happens
},
}
);
};

ReferenceError: onclick function is not defined

I've gotten a "ReferenceError: function is not defined on the saveRoute function". Everything seems right to me but i could not figure out the problem.
Here is the related codes.
<script type="text/javascript">
var array = routeobj;
function saveRoute(){
var json = JSON.stringify(array)
$.ajax({
url : "http://192.168.1.9:11123/runornot/drawtrack",
type: "POST",
dataType:'json'
data : {json:json}
{"routeJson": json },
console.log("hellohelloworldolr");
success: function(data, textStatus, jqXHR)
{ //data - response from server
console.log("checkin success"); },
error: function (jqXHR, textStatus, errorThrown)
{
}});}
</script>
and in the html
Save
<script type="text/javascript">
var array = routeobj;
function saveRoute(){
var json = JSON.stringify(array) // <--- best practice would require a semicolon here
$.ajax({
url : "http://192.168.1.9:11123/runornot/drawtrack",
type: "POST",
dataType:'json' // <--- missing a comma
// the structure doesn't make any sense starting here...
data : {json:json} // <--- should be a comma here?
// missing property name?
{"routeJson": json },
// is this supposed to be the body of a function?
console.log("hellohelloworldolr");
// things start making sense again here...
success: function(data, textStatus, jqXHR)
{ //data - response from server
console.log("checkin success"); },
error: function (jqXHR, textStatus, errorThrown)
{
}});}
</script>

JQuery ajax() done / fail callbacks not returning upon status 200

I'm trying to post a form data using JQuery to a remote servlet.
I can see that the server receives the data and also returns status code 200 and a response string of "{result: 'success'}"
But the ajax call doesn't return with the done or fail functions (if I add an always function than I can see that it is being called)
Here's a code snippet of the client side:
`
var dataParams = 'email='+email+'&password='+password;
var url = 'http://127.0.0.1:8888/signup';
var jxhr = $.ajax({
type : "POST",
url : url,
data : dataParams,// serializes the form's elements.
dataType: "json",
done: function() {
console.log("done!");
hideSignUp();
showThankYou(); },
fail: function() {
console.log("fail!");
}
});
`
Seems like I'm missing out on something, but can't seem to find what.
Note that I'm using JQuery 1.8.3 so success is deprecated.
Any thoughts?
Try:
var url = "http://127.0.0.1:8888/signup";
var jxhr = $.ajax({
type : "POST",
url : url,
data : dataParams,// serializes the form's elements.
dataType: "json"
}).done(function() {
console.log("done!");
hideSignUp();
showThankYou();
}).fail(function(jqXHR, textStatus) {
console.log(textStatus);
});
Try chaining your callbacks, rather than setting them as object fields:
$.ajax({
type : "POST",
url : url,
data : dataParams,// serializes the form's elements.
dataType: "json"
}).done(function (xhrResponse) {
console.log("done!");
hideSignUp();
showThankYou();
}).fail(function (xhrResponse, textStatus) {
console.log(textStatus);
}).always( function () {
console.log("I'm done with this.");
});
By chaining your callbacks, you guarantee execution of at least one (complete).

Categories

Resources