Need some help combining 2 jQuery scripts and behaviors - ajax

Ι need to use a combination of the following 2 scripts but despite all the combinations I've done so far, I fail to get it to work 100%.
I use a colorbox to display products detail pages in which there is a form with various fields for adding the items to the cart. Upon submitting the form, I want to show an alert and then close the colorbox so that the underlying page (that opened the colorbox in the forst place) stays as is.
With this script
$("#productadd").submit(function(){ // WORKS FINE EXCEPT THE ENCODING
$.post(
$(this).attr('action'),
$(this).serialize(),
function(data){
alert('Product was added to your order');
$().colorbox.close();
});
everything works fine except for the encoding which in my case is iso-8859-7 (greek).
If I use this script then encoding is ok but the post is being made with the default behaviour, redirection to the url defined in the form's action.
$("#productadd").submit(function(){ //ENCODING OK, COLORBOX.CLOSE() AND ALERT FAIL
$.ajax({
data: data,
type: "POST",
url: $(this).attr('action'),
dataType: 'json',
beforeSend : function(xhr) {
xhr.setRequestHeader('Accept', "text/html; charset=iso-8859-7");
},
success: function(json) {
alert('Product added to cart!'),
$().colorbox.close(),
itemAddCallback(json);
},
error: function (xhr, textStatus, errorThrown) {
$("#error").html(xhr.responseText);
}
});
If there's a jQuery equivalent for xhr.setRequestHeader('Accept', "text/html; charset=iso-8859-7") I'd be more than happy to use it. Also, what do I declare as data: so I dont get a 'data is not defined' error? (despite the error, date submits fine).
UPDATE: After various suggestions from those who answered so far, this is what my code looks like:
$("#productadd").submit(function(){
$.ajax({
data: $(this).serialize(),
type: "POST",
url: $(this).attr('action'),
dataType: 'text',
mimeType: "text/html; iso-8859-7",
success: function() {
alert('Item added to your order'),
$().colorbox.close();
},
error: function (xhr, textStatus, errorThrown) {
$("#error").html(xhr.responseText);
}
});
My only problem is that although it submits and displays the alert etc, the submitted data is encoded in utf-8 instead of iso-8859-7, any ideas?

Please check the documentation:
http://api.jquery.com/jQuery.ajax/
Find mimeType property.
mimeType(added 1.5.1)String
A mime type to override the XHR mime type.
Therefore you need to add following:
$.ajax({
data: data,
type: "POST",
mimeType: "text/html; charset=iso-8859-7"...

In the shorthand POST request you send $(this).serialize() as data, so I suppose you want to send the same form data in the other request.
To debug the requests, use your browsers net panel and find out if the requests actually fire and what the responses are (F12 then Net > XHR).
Hope this helps!

Related

Laravel cant submit ajax forms appended by javascript

I have implemented infinite scroll that appends html in the exact same manner as the static item with forms (inclusive csrf), but the dynamic forms that has been appended seems to be submitting without ajax and failing when pressing the submit button.
I get this error on the appended forms in console log:
Resource interpreted as Document but transferred with MIME type application/json:
The ajax submit.
$('.cart_add').on('submit',function (event) {
$.ajax({
type: 'POST',
url: url,
data: data,
beforeSend: function (request) {
return request.setRequestHeader('X-CSRF-Token', $("meta[name='csrf-token']").attr('content'));
},
success: function (data) {
console.log("item has been added to cart");
event.preventDefault();
}
});
});
Edit I noticed that the jquery doesn't select the dynamically appended forms
Try setting your content type. The content type is the type of data sent to the server. In this case, you are sending data to the server which is interpreted as a Document (html) but is sent as json. This is because the browser is trying to infer what type of data your are sending becuase you did not explicitly state it.
Use the contentType to set it.
contentType: "text/html"
So your call should look like this:
$.ajax({
type: 'POST',
url: url,
data: data,
contentType: "text/html",
beforeSend: function (request) {
return request.setRequestHeader('X-CSRF-Token', $("meta[name='csrf-token']").attr('content'));
},
success: function (data) {
console.log("item has been added to cart");
event.preventDefault();
}
});

jQuery Ajax POST changes Content-Type in Firefox

I'm making an Ajax call to POST a collection of fields, objects, and arrays to PHP. 9 times out of 10 this works just fine. But when submitting the same request a number of times (no changes to the data) the request will occasionally be sent with Content-Type: text/plain or text/html rather than application/x-www-form-urlencoded, causing issues in my PHP. JSON might be more advisable, but can anyone think of why this could be happening?
This is not a cross domain request.
This only happens in Firefox.
I don't think I need to specify the Content-Type since Ajax will default.
I explicitly call $.param() but don't think I need to.
I expect JSON in return.
$.ajax({url: action,
type: "POST",
dataType: "json",
data: $.param($(domElement).data()),
complete: function() {
// Cleanup
},
success: function(data) {
// Handle success.
},
error: function() {
// Handle error
}
});
Not sure why this only happens in Firefox, but does it help if you set the content type manually?
$.ajax({url: action,
type: "POST",
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
dataType: "json",
data: $.param($(domElement).data()),
complete: function() {
// Cleanup
},
success: function(data) {
// Handle success.
},
error: function() {
// Handle error
}
});

jquery ajax data shows [object Object]

I have a very basic ajax call to alert the data that was reported from the server
$.ajax({
type: "POST",
url: "/someform/act", //edit utl to url
data: { changed: JSON.stringify(plainData) }, //edit to include
success: function(data) {
alert(data); //data not $data
},
error: function() {
//error condition code
}
});
According to the docs on the jquery website regarding data field on the success callback, it says that data returned is the data from the server. However for some strange reason when I alert $data, I get [object Object]
I was expecting to see something like this, since that is what the server would send back
<status>0</status>
EDIT:
data is also passed along as the POST
You need to use JSON.stringify(data) in the alert to get anything readable.
Also, $data is a completely different variable name than data.
alert() prints the string representation of the arguments - hence if you pass an object, you'll get [object Object].
To inspect data, use console.log(data) better.
If you server send a JSON, you need to put dataType: 'json' to your ajax call. Be aware there's some mistake in your ajax call.
$.ajax({
type: "POST",
url: "/someform/act", // NOT 'UTL',
data: {
key: value,
key2: value2
},
// or data: plaindata, // If 'plaindata' is an object.
dataType: 'json',
success: function(data) {
console.log(data); // As moonwave99 said
},
error: function() {
//error condition code
}
});
EDIT
When sending data, you should send an object. jQuery will handle the array to sned it to the server. So if plain data is an object, it should be like this
data: plainData,
If you're sending data via $.ajax({...}), the Network tab of your browser inspector might be showing [object Object] in the Payload (Chrome) / Request (Firefox) sub-tab, like in the following image (Firefox):
The reason for this might be in the way you're forming your AJAX call. Specifically:
$.ajax({
url: '/ajax/example-endpoint',
data: {'fooKey':fooData,'barKey':barData},
type: 'post',
cache: false,
contentType: false, // this one will turn your data into something like fooKey=fooData&barKey=barData
processData: false, // and this one will make it [object Object]:""
beforeSend: function() {
// whatever it is you need to do
},
success: function(data) {
// do stuff
},
error: function(desc, err) {
// do stuff
}
});
When combined, contentType: false and processData: false turn your data into [object Object], because you're actually telling your AJAX call to ignore the content type of whatever is being sent, and not to process it.
If it's IIS, try creating a site outside of the Default Web Site (for example localhost/ajax1). For example a new site ajax1, place it not in the DefaultAppPool, but in your pool, for example ajax1. Try http://ajax1

Jquery AJAX for fetching JSON, affected by URL prefix (www vs. no www)?

I have come across a peculiar item in JQuery that I am hoping somebody can help me to understand.
I've spent much of the day trying to get JQUERY's AJAX 'success' function to be raised when returning JSON from the server.
I checked the JSON # JSONLint to ensure validity, checked encoding, tried different headers, but still PROBLEMS.
After a couple hours, I switched the url (by accident!)
from
http//www.testing.com/_r4444/myfile.php
to the exact same thing WITHOUT the www... and it suddenly worked.
I have no clue why this would be the case - any ideas?
the snippet follows
$(document).ready(function() {
$.ajax( {
type: "POST",
contentType: "application/json",
url: "http://testing.com/_r4444/getter.php",
beforeSend: function(x) {
if(x && x.overrideMimeType) x.overrideMimeType("application/json;charset=UTF-8");
},
data: "pass=TEST",
dataType: "json",
error: function (xhr, status) {
alert(status);
},
success: function (result) {
alert(result);
}
});
});
Are you using "www" on the page in the browser?
Try switching the call to not include the domain, like:
"/_r4444/getter.php" instead of the full domain.

Jquery: probleme with $.ajax (json datatype)

I have a problem to refresh a bloc in my page.
Here is the request:
> $("#pwd_lost_link").click(function(){
alert('1');
$.ajax({
type : 'POST',
url: 'test.php',
dataType: 'json',
data :{"nom" : "akbar"},
success : function(data){
$("#main_bloc").append(data.msg);
alert('2');
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest.responseText);
alert(errorThrown); }
}); })
and here is the php file
<?php
$return['nom'] = "ffrfrfrfr";
echo json_encode($return)
?>
It doesn't work. It give me a status error ( 0 ) and the page is automatically reloaded
Thanks
Michaël
Confusing question Michael, not sure what you mean by "the page is automatically reloaded" but you should do 2 things:
In the $.ajax() method, make sure your success called back is handling the data correctly. You are looking for data.msg but I don't see where .msg comes from.
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
data: {},
dataType: "json",
url: url,
success: function(data) {
// parse data object so you can see what's being returned ex. alert(data) or alert(data[0]) or alert(data.nom)
},
error: function (xhr, status, error) {
// XHR DOM reference: http://www.w3schools.com/dom/dom_http.asp
// check for errors ex. alert(xhr.statusText);
}
});
On the PHP side, you may want to debug there to see what is being received and what you are sending back.
Aside from that using an XHR viewer like Firebug or Chrome's built-in utility (CTRL+SHIFT+I) can be very helpful.
And on a final note, if pwd_lost_link is a link elment a id="pwd_lost_link" href="..." then you will have to stop the browser from following the link before you process the AJAX.
$("#pwd_lost_link").click(function(e) {
e.preventDefault();
alert('1');
$.ajax({
...
});
If you aren't seeing the '1' being alerted then that is definitely your first problem.
You're trying to access data.msg, but your PHP script is only creating data.nom. So data.msg doesn't exist. Try changing data.msg to data.nom and see if this does what you want.

Resources