Laravel cant submit ajax forms appended by javascript - ajax

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();
}
});

Related

Linking AJAX with PHP code. Do i need to write it again?

I have a real problem. I have a php code and a form where when the form is submitted a POST request is sent and the page reloads again and ofcourse the post is viwed in the page.But i want to work with AJAX in order page not to be refreshed.I know the basics of AJAX but i don't want to build all the project from the beggining.Is there a way in success function of AJAX to link to my php code??
$.ajax({
type: "POST",
url: "index.php",
datatype: "html",
data: dataString,
success: function(data) {
//How can i link here to start running my php code which is located in the same page.
}
});
$.ajax({
type: "POST",
url: "somescript.php",
datatype: "html",
data: dataString,
success: function(data) {
// try this
console.log(data);
// see what 'data' actually is
}
});
then check in the browser by hitting F12 to look at the console.
also are you sure you want datatype of html ? you probably want a data type of json or XML , what is the server returning to you after the ajax post?
You have to cancel the form's submission so that the ajax request will take place, otherwise it is canceled. Also use .serialize to get a name-value pair string of the form data to use in the ajax call.
Html
<form id="MyForm">
<button id="MyButtonId">Submit</button>
</form>
JS
$("#MyForm").submit(function(e){
//Prevents the form from being submitted
e.preventDefault();
$.ajax({
type: "POST",
data: $("#MyForm").serialize(),
url: "somescript.php",
datatype: "html",
data: dataString,
success: function(data) {
alert(data);
}
});
});

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

Need some help combining 2 jQuery scripts and behaviors

Ι 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!

How use Facebook Javascript SDK response in Ajax request?

Supposing I have the following code which returns a Javascript object which I can read in Firebug's console:
FB.api('/me',function(apiresponse){
console.log(apiresponse);
});
How can I then use the data from apiresponse in an Ajax request on the same page?
Currently my Ajax request looks as follows:
$.ajax({
// CodeIgniter URL
url: "<?=site_url?>('login/add_fb_users'); ?>",
type: 'POST',
data: apiresponse,
success: function(data) {
alert(data);
}
});
I know very little about Javascript, but reading around the subject leads me to think I have to convert the Javascript object to a JSON string. Is that correct? Am I on the right track?
You could put your AJAX call inside the handler for the API call like below..
FB.api('/me', function(apiresponse){
console.log(apiresponse);
$.ajax({
// CodeIgniter URL
url: "<?=site_url?>('login/add_fb_users'); ?>",
type: 'POST',
data: apiresponse,
success: function(data) {
alert(data);
}
});
});
one possible way:
define a global variable in your javascript, e.g. var myVar1;
set apireponse to the global variable in your FB.api callback (i.e. where u call console.log)
reference the var myVar1 in your ajax fcn.

using ajax in a page loaded by ajax

i have a page loaded via jquery tabs ajax, i have a form within this page that i want to show form response via ajax. response is loading from this code:
$('#whois').submit(function() {
$.ajax({
data: $('#whois').serialize(),
cache:false,
type: "POST",
url: $('#whois').attr('/lib/domainchecker.php'),
success: function(response) {
$('#reply').html(response);
}
});
return false;
);
but my form submit to parent page instead of /lib/domainchecker.php. so i see headers of my page instead of response!
any idea what makes this happen?
When you are loading content on the page via AJAX and you need to apply events to the loaded content you need to use the jquery live().
$('#whois').live('submit', function() {
$.ajax({
data: $('#whois').serialize(),
cache:false,
type: "POST",
url: $('#whois').attr('/lib/domainchecker.php'),
success: function(response) {
$('#reply').html(response);
}
});
This of course goes on the main host page rather than the loaded content page.
problem is solved, no thing related to loading page via ajax but there was an error with code, i shouldn't post to $('#whois').attr('/lib/domainchecker.php') but just '/lib/domainchecker.php'
corrected code:
$('#whois').live('submit', function() {
$.ajax({
data: $('#whois').serialize(),
cache:false,
type: "POST",
url: '/lib/domainchecker.php',
success: function(response) {
$('#reply').html(response);
}
});

Resources