post form with ajax and additional json data - ajax

I send a form via jquery ajax. I do not only want to send the values of the formcollection I also want to send another id which is hidden in the page.
How can I send the form data + this id? Maybe there is a way to create one json object and I put everything in it?
jQuery('#myForm').live('submit',function(event) {
$.ajax({
url: 'Url.Action("Create")',
type: 'POST',
data: $('#myForm').serialize(),
success: function( data ) {
}
});
return false;
});

If your hidden field is already in the form, It will be in your serialized data. You dont need to send it exclusively. If you still want to send another piece of data from outside of your form, you may send it as a querystring value and have your action method a parameter named itemId.(Assuming hdnID is the id of your hidden element)
$.ajax({
url: '#Url.Action("Create","Home")'+?itemId='+$("#hdnID").val(),
type: 'POST',
data: $('#myForm').serialize(),
success: function( data ) {
}
});
http://api.jquery.com/serialize/

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

Retrieve post value in the controller sent by ajax call

I am unable to retrieve value sent as a post through ajax call in cake php controller file
$.ajax({
type: "POST",
url: "share",
data: country,
dataType: "json",
success: function (response) {
if (response.success) {
// Success!
} else {
console.log(response.data, response.code);
}
}
});
I have tried with the below ways of retrieving the data sent in the above code through POST. But none of them worked.
$this->params
$this->data
$_POST[]
$this->request
The url points to the function in the controller page.
Please can any of you let me know how the value can be retrieved.
When submitting data via ajax and you want cake to pick it up in the usual way just use $('whatever').serialize().
if you don't have an actual form to serialize you can fake it by submitting the data as follows:
$.ajax({
...
data: {
data: country
},
...
});
Note how cake generates fields like data[Model][field]. you don't need the Model part but the data part is important.

ajax request in jquery, data sent to the server not working

var p = JSON.stringify(parameter);
console.log(p);
$.ajax({
type: 'POST',
url: 'http://abc.com/ajax.php',
data: p,
success: function(status) {
console.log(status);
}
});
console.log(p) shows {"o_fname":"hh","o_lname":"jkhk","o_email":"uifh#bjvh.com","o_phone":"","b_name":"bmnbmbm,b","b_address":"","b_city":"","b_postal":"","b_phone":""}
but in my http://abc.com/ajax.php page print_r($_POST) is giving me an empty array Array()
var p = JSON.stringify(parameter);
That is your problem.
When you pass string data to .ajax, it sends it “as-is” – but PHP only popuplates $_POST if it receives data encoded as application/x-www-form-urlencoded.
So don’t make your data into a string, but pass your parameter object directly as value for data – then jQuery will take care of sending it the right way, so that PHP understands what it is supposed to do with it.
I think park of the problem may be that in data: you're passing the parameter details, but to the function on the other side of the jQuery you're passing a parameter name and nothing else.
Try:
$.ajax({
type: 'POST',
url: 'http://abc.com/ajax.php',
data: {parametername:p},
success: function(status) {
console.log(status);
}
});
With parametername replaced with the parameter name ajax.php is expecting.

jquery ajax send string as POST

I am developping a wordpress plugin, want to send string as post ajax parameters, but the string breaks with '&'
code is
var data = "http://localhost/wordpress/?page_id=1&setval=RFZ83WSXa816yc6DNcgfHlgIkztR7KEC6JHRHCCcwfw|~HBZW9j3B59f8rCXO_QLY-gG2MDAcKo6fKG2AnbYnMns|~KA1KUT_SuU9W2UDTnngTsbJiptTvGWZAAzTfN5BCHak|~1";
$.ajax({
data: data
type: "POST",
url: '<?php echo plugins_url().'/page-loader/createMetaDetails.php'; ?>',
data :data,
success: function(msg){
alert('wow'+msg);
}
});
it is not working only passing till 'http://localhost/wordpress/?page_id=1', why?
You need to put data in key value pair array to pass jquery ajax function.
change
var data = 'http://localhost/wordpress/?page_id=1&setval=RFZ83WSXa816yc6DNcgfHlgIkztR7KEC6JHRHCCcwfw|~HBZW9j3B59f8rCXO_QLY-gG2MDAcKo6fKG2AnbYnMns|~KA1KUT_SuU9W2UDTnngTsbJiptTvGWZAAzTfN5BCHak|~1'
To
var data = { yoururl:'http://localhost/wordpress/?page_id=1&setval=RFZ83WSXa816yc6DNcgfHlgIkztR7KEC6JHRHCCcwfw|~HBZW9j3B59f8rCXO_QLY-gG2MDAcKo6fKG2AnbYnMns|~KA1KUT_SuU9W2UDTnngTsbJiptTvGWZAAzTfN5BCHak|~1'}
The data property should be a Javascript object in key:value format; the keys will be the form field names.

MooTools: How do package data for a POST ajax request?

I'm using MooTools 1.4.1. I want to create an ajax post requst, but I can't figure out how to construct the "data" attribute, which I wish to contain the name value pairs of a form whose id is "myForm".
$('save').addEvent('click', function(event) {
var req = new Request({
method: 'post',
url: 'save',
data: { ... },
onRequest: function() {
// on request
},
onComplete: function(response) {
alert(response);
});
});
Anyone know how I should populate the "data" attribute? Thanks, - Dave
You can use
$('myForm').toQueryString();
Alternatively, The MooTools More package has a Form.Request() class to send a Form using Ajax.
As Savageman commented, you can throw your form element into toQueryString() and send it through in the data property, or by running .send() or .post() on the request object.
You also seem to be missing a closing squiggly bracket.
Anyhow, this is how I make AJAX requests:
new Request({
url: 'http://url/to/ajax/script.php',
onSuccess: function(data) {
doStuff();
}
}).post('action=foo&bar=baz');
I'd recommend you use Request.JSON if you're planning on sending stuff back. It's less "shotgun approach"-ey.
You can just pass form element to "data" property, and conversion is automatic.
var req = new Request({
method: 'post',
url: 'example.com/form.php',
data: $('myForm'),
onRequest: function() {
// on request
},
onComplete: function(response) {
alert(response);
}
});
data - (mixed: defaults to '') The default data for Request:send, used when no data is given. Can be an Element, Object or String.
If an Object is passed the Object:toQueryString method will be used to convert the object to a string.
If an Element is passed the Element:toQueryString method will be used to convert the Element to a string.
http://mootools.net/docs/core/Request/Request

Resources