Submitting a form using jQuery and Ajax changing the action - javascript

I have a form, which I am trying to submit using jQuery and AJAX. I am triggering the submit by clicking on a link, which I've added an onclick method. Below are two code samples to submit the same form - the first works, but isn't AJAX, while the second method gives me a 404 error.
function submitmyform(formid) {
$(formid).submit();
}
The second example attempts to use AJAX, given the same parameters:
function submitmyformajax(formid) {
$.post({
type: "POST",
url: $(formid).attr('action'),
data: $(formid).serialize(),
success: function(data) { alert(data); }
});
}
An alternate way I tried with the submitmyformajax is:
function submitmyformajax(formid) {
$.post({
type: "POST",
url: 'somehardcoded/url',
data: $(formid).serialize(),
success: function(data) { alert(data); }
});
}
For some reason, this continues to give me a 404 error, though the action on the form is correct (the URL it shows me is not the same as the action on the form).
I checked the error console, and it shows the 404 error as pointing to somehardcoded/[object%20Object] instead of what I specified in the method.
What am I doing wrong?

I think you are getting $.post and $.ajax mixed up. $.post is short hand for $.ajax, as such takes a string url as first parameter, an object as the data, and a function as the callback. $.ajax on the otherhand takes an object as configuration, as you are doing
i.e. Post signature is
$.post( url [, data ] [, success(data, textStatus, jqXHR) ] [, dataType ] )
which is shorthand for
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
You seem to be using a mixture of both, and hence getting strange behavior, as it is calling toString on the first parameter you are passing in to the $.post which is [object Object] and then that is url encoded to [object%20Object]
Either use
$.post($(formid).attr('action'),
$(formid).serialize(),
function(data) { alert(data); })
or
$.ajax({
type: "POST",
url: $(formid).attr('action'),
data: $(formid).serialize(),
success: function(data) { alert(data); }
});

use this instead..
$.post(
'somehardcoded/url',
{data:$(formid).serialize()},
function(data) {
alert(data);
}
);

Related

Ajax request not working when a function is added to the success option

I am having trouble getting an ajax GET request (or any request for that matter) to retrieve the response. I am simply trying to return the response in an alert event:
<script>
$(document).ready(function() {
$('#test').click(function() {
$.ajax ({
type: 'Get',
url: 'https://crm.zoho.com/crm/private/json/Potentials/searchRecords?authtoken=XXX&scope=crmapi&criteria=(((Potential Email:test#email.com))&selectColumns=Potentials(Potential Name)&fromIndex=1&toIndex=1',
dataType: 'json',
success: function(data) {
alert(data);
}
});
});
});
</script>
I can get this and other similar post requests to work by taking away the function in the success option and editing the code like this:
<script>
$(document).ready(function() {
$('#test').click(function() {
$.ajax ({
type: 'Get',
url: 'https://crm.zoho.com/crm/private/json/Potentials/searchRecords?authtoken=XXXX&scope=crmapi&criteria=(((Potential Email:test#email.com))&selectColumns=Potentials(Potential Name)&fromIndex=1&toIndex=1',
dataType: 'json',
success: alert('success')
});
});
});
</script>
Why is this? And more importantly, how can I retrieve the response data and transfer it to an alert message? Any help is appreciated!
** Update:
Upon reading the first two users' responses on this question, this is what I have:
<script>
$(document).ready(function() {
$('#test').click(function() {
$.ajax ({
type: 'GET',
url: 'https://crm.zoho.com/crm/private/json/Potentials/searchRecords?authtoken=418431ea64141079860d96c85ee41916&scope=crmapi&criteria=(((Potential%20Email:test#email.com))&selectColumns=Potentials(Potential%20Name)&fromIndex=1&toIndex=1',
dataType: 'json',
success: function(data) {
alert(JSON.stringify(data));
},
error: function(data) {
alert(JSON.stringify(data));
}
});
});
});
</script>
I am able to get the error response, so I can confirm there is some kind of error. I also want to point out that I am making the request from a different domain (not crm.zoho.com) so should I be using jsonp? If so, how would I alter the code?
When you have
success: alert('success')
you do NOT have a successful request, you are actually executing this function at the start of AJAX method. The success parameter requires a pointer to a function, and when you use alert('success') you are executing a function instead of providing a pointer to it.
First thing that you need to try is to update type to GET instead of Get:
$.ajax ({
type: 'GET',
Try using the .done() function as follows:
<script>
$(document).ready(function() {
$('#test').click(function() {
$.ajax ({
type: 'Get',
url: 'yourUrl',
dataType: 'json',
}
}).done(function(result) {alert(data);}) //try adding:
.error(function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);})
});
});
the error function will also give you some information in your console as to the status of your request.

jQuery .ajax call never calling method

In this SO post I learned how to get a return value from an AJAX call:
function CallIsDataReady(input) {
$.ajax({
url: "http://www.blah.com/services/TestsService.svc/IsDataReady",
type: "GET",
contentType: "application/json; charset=utf-8",
data: input,
dataType: "json",
success: function (data) {
if (!data) {
setTimeout(function (inputInner) { CallIsDataReady(inputInner); }, 1000);
}
else {
//Continue as data is ready
callUpdateGrid(input);
}
}
});
}
$(document).ready(function () {
var input = { requestGUID: "<%=guid %>" };
CallIsDataReady(input);
});
This function calls its web service wich does return true. The problem is that inside the following callUpdateGrid, the logging shows that that web service method is not getting called from the $.ajax call:
function callUpdateGrid(input) {
console.log(input);
$.ajax({
url: "http://www.blah.com/services/TestsService.svc/GetContactsDataAndCountbyGUID",
type: "GET",
contentType: "application/json; charset=utf-8",
data: input,
dataType: "json",
success: function (data) {
var mtv = $find("<%= RadGrid1.ClientID %>").get_masterTableView();
console.log(data);
mtv.set_dataSource(data.d.Data);
mtv.dataBind();
}
});
}
Anyone know what is wrong?
It is always a good idea to include an error handler function as one of the options passed to $.ajax. For example, add this code after your success functions:
,
error: function(jqXHR, textStatus, errThrown) {
console.log("AJAX call failed");
console.log(errThrown);
}
That will log at least a bit of information if the $.ajax call doesn't succeed.
EDIT
According to your comment, this logs
SyntaxError: Invalid character
And in fact, I now see that you are giving a plain JavaScript object as the data option passed to $.ajax, but indicating that it is a JSON object in the dataType field. You need to actually convert the input object into JSON yourself, like so:
data: JSON.stringify(input),
dataType: 'json',
Alternatively, you could simply format input as a JSON object in first place, like so:
var input = { "requestGUID": "<%=guid %>" };
The quotes around the field name requestGUID are sufficient, in this case, to give you a JSON object.

AJAX: How to use returned array?

I have an ajax POST that sends data to a controller function and that function returns a string array back to the ajax call as the default 1st parameter in the ajax success method. When I tried to use the returned data, it won't let me print the 1st element to an alert box. How come?
i.e.
$.ajax(
{
type: "POST",
url: "../Home/stringSplitFunct",
data: { 'parameter1': Input },
success: function (response)
{
alert(response[0]);
}
});
In fact, I don't think it even recognize it as a string array.
You need to specify dataType. Read more here.
$.ajax({
type: "POST",
url: "../Home/stringSplitFunct",
data: { 'parameter1': Input },
dataType: 'json',
success: function (response)
{
alert(response[0]);
}
});
Looks like the data is being returned as a raw sting.
Use dataType property for your ajax request
dataType: 'json'
Also avoid using alert as it stops the execution flow. Use console.log instead

Sending ASP.NET Model through AJAX

I'm trying to send part of a model through an ajax call, but doing it simply like my code below, doesn't work. How could I pass this object along?
$.ajax({
url: "/Controller/Action",
type: "GET",
data: #Model.Company,
success: function (result) {
$('#myDiv').html(data);
}
});
This is what my JS puts outs:
MyProj.Domain.Entities.Company
This is my error:
Uncaught ReferenceError: MyProj is not defined
Your syntax would work fine for a primitive variable, but you should serialize your object to Json before sending. And also make sure that script stays in cshtml or aspx page, else '#Html' helper will not work.
$.ajax({
url: "/Controller/Action",
type: "GET",
data: #Html.Raw(Json.Encode(Model.Company)),
success: function (result) {
$('#myDiv').html(data);
}
});

How do I access a returned value from a .ajax request within the done() function

Here's my function which returns a name of a person.
function getName(ID){
return $.ajax({
url:url,
data: ID,
type: 'get',
dataType: 'json'
});
}
And here is where I am attempting to use the .done() function.
getName("1").done() // How do I ref the returned var in our done function?
I am confused on how to reference the returned value from my getName function within my done function.
I know I could do this using success: within the .ajax, but I am trying to move away from that and used deferred objects.
Thanks!
it look slike done requires a callback function that takes a parameter with the data recieved from teh request.
http://api.jquery.com/jQuery.ajax/
getName("1").done(function(response) {
alert(response);
});
It's right there in the documentation:
//Example: Save some data to the server and notify the user once it's complete.
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
//Example: Retrieve the latest version of an HTML page.
$.ajax({
url: "test.html",
cache: false
}).done(function( html ) {
$("#results").append(html);
});
Also, make sure you read this, because, depending on the Datatype you might actually "receive" not a simple string/id but possibly an object parsed from a JSON/XML result or...

Categories