I'm trying to upload a image to my server using a POST form and AJAX. But everytime I submit the form, my AJAX returns an undefined in my error box. This is the Ajax function I'm talking about:
$('.register_submit').click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "./functions/register.php",
data: new FormData(this),
contentType: false,
processData: false,
success : function(data){
if (data.code == "200"){
window.location.replace("./?page=home");
} else {
$(".display-error").html("<ul>"+data.msg+"</ul>");
$(".display-error").css("display","block");
}
}
});
});
and my form:
<form class="addCar_form" data-toggle="validator" method="post" enctype="multipart/form-data" >
<input type="file" class="form-control productimages" id="images" name="images[]" onchange="preview_images();" multiple/>
<input type="submit" name="addCar_submit" value="Auto toevoegen" class="btn btn-default button addCar_submit">
</form>
Please do not mark this question as a duplicate, as I've been reading about ajax and it being asynchronous in other topics but I'm really not getting it from these answers. Anyone who sees what I'm doing wrong?
The click handler for $(".register_submit") would be targeting the button; then the button is passed in through FormData(this). FormData should instead contain a reference to the form...
Also, I don't see a register_submit class definition on the form in this example, so maybe it's getting overlooked?
In your PHP page, can you trace through it to see what form data is being passed? That is helpful to track down these kinds of problems, by evaluating the form posted data.
I think your server returns an error with a different status code. Therefor the success callback might not be called.
There are different callback available for $.ajax I think error is the one you need to check.
From the docs:
error callback option is invoked, if the request fails. It receives the jqXHR, a string indicating the error type, and an exception object if applicable. Some built-in errors will provide a string as the exception object: "abort", "timeout", "No Transport".
Try:
$('.register_submit').click(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "./functions/register.php",
data: new FormData(this),
contentType: false,
processData: false,
success: function (data) {
if (data.code == "200") {
window.location.replace("./?page=home");
} else {
$(".display-error").html("<ul>" + data.msg + "</ul>");
$(".display-error").css("display", "block");
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
});
Related
Good day, i need past variable in post to other file
}
$.ajax({
url: 'emps.php',
type: 'POST', // GET or POST
data: {"sucursal":$("#suc").val()},
success: function(data) { // data is the response from your php script
// This function is called if your AJAX query was successful
alert(data);
},
error: function() {
// This callback is called if your AJAX query has failed
alert("Errors!");
}
});
}
code variable
<tr>
<td class="col1"><label for="pat">Sucursal:</label></td>
<td class="col2">
<input type="text" name="suc" id="suc" class="medium" readonly="true" style="width: 200px;"size="40" maxlength="200" onChange="javascript:this.value=this.value.toUpperCase();" />
<input type="button" class="btn btn-success btn-sm" id="sbm" name="sbm" value="Buscar" onclick="llenaSucursales()" />
</td>
</tr>
Error image is :
whats its a problem?
I await your help and I started reading and search and can not find the error
You should have a look at the jQuery documentation for $.ajax() to understand what you may use to react on errors in your AJAX call:
$.ajax({
url: 'emps.php',
type: 'POST', // GET or POST
data: {"sucursal":$("#suc").val()},
success: function(data) { // data is the response from your php script
// This function is called if your AJAX query was successful
alert(data);
},
error: function(jqXHR, status, errorThrown) {
// This callback is called if your AJAX query has failed
alert('Got the error ' + errorThrown + ' with status ' +status);
}
});
I would also recommend to open up the Developer Tools (F12 in most browsers) and check the "Network tab" to see the responses of AJAX calls.
Not related to your question:
In the future please take more care when writing your post. Remove unnecessary blank lines, don't post code with errors (just concentrate on the important parts of what you post) - thanks.
The error was that I was missing "/" the address of the file, Thanks, then I leave the code
function empleados(){
if($("#suc").val()=='')
{
alert('Elige una sucursal');
return false;
}
$.ajax({
url: '/emps.php',
type: 'POST', // GET or POST
data: {"suc":$("#suc").val()},
success: function(data) { // data is the response from your php script
// This function is called if your AJAX query was successful
alert(data);
},
error: function() {
// This callback is called if your AJAX query has failed
alert("Errors!");
}
});
}
I am implementing a simple CRUD operating. I have List of data displayed in table with capability of add edit and delete. Add edit and delete operation takes place in Jquery dialog
When i am trying to add a new record I return the Json result as Success True/false depending on the form data entry.
Here is my code
[HttpPost]
public ActionResult AddUser(AddCEQRUser addUserInfo)
{
// perform insert operation
if (ModelState.IsValid && InsertSuccess)
return Json(new { success = true }, JsonRequestBehavior.AllowGet);
else
return Json(new { success = false }, JsonRequestBehavior.AllowGet);
}
Partial view for add
#using (Html.BeginForm("AddUser", "Admin", FormMethod.Post, new { id = "addUserForm" }))
{
#Html.AntiForgeryToken()
<fieldset>
<table class="headertable">
// form elements
<tr>
<td align="center" colspan="2">
<button name="button" value="SubmitUser" class="button" id="btnSubmitUser">
Submit
</button>
<button name="button" value="CancelAddUser" class="button" id="btnCancel">
Cancel
</button>
</td>
</tr>
</table>
</fieldset>
}
Ajax call on Submit button
$('#btnSubmitUser').click(function () {
$.ajax({
url: '#Url.Action("AddUser", "Admin", new { Area = "PrivateCEQRApplication" })',
type: 'POST',
dataType: 'json',
cache: false,
headers: headers,
data: {
FirstName: $('#txtFirstNameAdd').val(),
MiddleName: $('#txtMiddleNameAdd').val(),
LastName: $('#txtLastNameAdd').val(),
EmailAddress: $('#txtEmailAddressAdd').val(),
UserRole: $('#ddlUserRoleSelectedAdd').val()
},
beforeSend: function (xhr, settings) { xhr.setRequestHeader('__RequestVerificationToken', token); },
success: function (data) {
if (data.success) {
alert("The user has been added.");
$(".ui-dialog-content").dialog().dialog("close");
}
else {
//error handling
}
},
error: function (xhr, textStatus, errorThrown) {
alert("There was a problem with the operation. Please try again" + "Status: " + textStatus + "Error: " + errorThrown);
}
});
});
Irrespective of whether there is an error or not when ever I click the Submit button I get a json file with { success : true } to download By IE.
I have read quite a few article about this and how it says to set Content type application/json or text/html
If i set content type to application/json I still get prompted to download and if i set text/html a new page opens with { success : true }.
I also noticed if i put e.preventDefault(); in my btnSubmitUser click event I don't get prompted for download but then i loose the error handling.
All I want is for dialog to close if there is no error (json success true) by executing this code
alert("The user has been added.");
$(".ui-dialog-content").dialog().dialog("close");
and display error if any by executing the json success false block.
Your help will be greatly appreciated.
Thanks
As Adeneo says, you have to prevent the default action of the form submit to allow the javascript to complete. You can do this by adding event.preventDefault(); as the first line of your function (just below $('#btnSubmitUser').click(function () {) or by having the function return false.
I am currently developping a new website
When I am trying to create an account, I get an error like this :
Uncaught TypeError: Cannot read property 'hasError' of null.
And this is the code
function submitFunction()
{
$('#create_account_error').html('').hide();
//send the ajax request to the server
$.ajax({
type: 'POST',
url: baseUri,
async: true,
cache: false,
dataType : "json",
data: {
controller: 'authentication',
SubmitCreate: 1,
ajax: true,
email_create: $('#email_create').val(),
back: $('input[name=back]').val(),
token: token
},
success: function(jsonData)
{
if (jsonData.hasError())
{
var errors = '';
for(error in jsonData.errors)
//IE6 bug fix
if(error != 'indexOf')
errors += '<li>'+jsonData.errors[error]+'</li>';
$('#create_account_error').html('<ol>'+errors+'</ol>').show();
}
else
{
// adding a div to display a transition
$('#center_column').html('<div id="noSlide">'+$('#center_column').html()+'</div>');
$('#noSlide').fadeOut('slow', function(){
$('#noSlide').html(jsonData.page);
// update the state (when this file is called from AJAX you still need to update the state)
bindStateInputAndUpdate();
$(this).fadeIn('slow', function(){
document.location = '#account-creation';
});
});
}
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{
alert("TECHNICAL ERROR: unable to load form.\n\nDetails:\nError thrown: " + XMLHttpRequest + "\n" + 'Text status: ' + textStatus);
}
});
}
It seems to be the jsonData, on the function, which is not working as well. Any idea or suggestions?
The success handler will be passed the data returned from the ajax request.
It will not have a function called hasError() because it is just a json object it will not have any functions.
The error handler should be fired if there is an http error i.e. if the ajax call returns an http 500.
I'm not familiar with prestashop, but looking over the prestashop documentation hasError is returned as a bool (not a function), so instead try (without the parenthesis).
if (jsonData.hasError)
You may also want to check if any data is returned first.
if (jsonData)
I am trying to POST some data to my ASP.Net MVC Web API controller and trying to get it back in the response. I have the following script for the post:
$('#recordUser').click(function () {
$.ajax({
type: 'POST',
url: 'api/RecordUser',
data: $("#recordUserForm").serialize(),
dataType: 'json',
success: function (useremail) {
console.log(useremail);
},
error: function (xhr, status, err) {
},
complete: function (xhr, status) {
if (status === 'error' || !xhr.responseText) {
alert("Error");
}
else {
var data = xhr.responseText;
alert(data);
//...
}
}
});
});
The problem with this script is that whenever I try to post the data, the jQuery comes back in "error" instead of "success".
I have made sure that there is no problem with my controller. I can get into my api method in debug mode whenever the request is made and can see that it is getting the data from the POST request and is returning it back. This controller is quite simple:
public class RecordUserController : ApiController
{
public RecordUserEmailDTO Post(RecordUserEmailDTO userEmail)
{
return userEmail;
}
}
I am not sure how I can get jQuery to print out any useful error messages. Currently when I try to debug the jQuery code using Chrome console it shows an empty xhr.responseText, nothing in "err" object and "status" set to "error" which as you see is not quite helpful.
One more thing that I have tried is to run the following code directly from the console:
$.ajax({
type: 'POST',
url: 'api/RecordUser',
data: {"Email":"email#address.com"},
dataType: 'json',
success: function (useremail) {
console.log(useremail);
},
error: function (xhr, status, err) {
console.log(xhr);
console.log(err);
console.log(status);
alert(err.Message);
},
complete: function (xhr, status) {
if (status === 'error' || !xhr.responseText) {
alert("Error");
}
else {
var data = xhr.responseText;
alert(data);
}
}
});
i.e. using the same script without actually clicking on the button and submitting the form. Surprisingly, this comes back with the right response and I can see my data printed out in console. For me this atleast means that my Web API controller is working fine but leaves me with no clue as to why it is not working on clicking the button or submitting the form and goes into "error" instead of "success".
I have failed to find any errors in my approach and would be glad if someone could help me in getting a response back when the form is posted.
As suggested by Alnitak, I was using complete callback along with success and error ones. Removing complete from my code fixed the issue.
Thanks to Alnitak.
I have a problem in my code, a button calls this ajax request from within a jQuery UI dialog
myaudioupload = $.ajax({
url: "some url",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (data) {
var data = jQuery.parseJSON(data);
console.log('json parsed');
if(data.status==1){
console.log('status ok');
}
else{
console.log('status not ok');
}
}
});
If the user wants to cancel the request, user closes the dialog box and then the following lines are executed:
close: function(event, ui) {
if(myaudioupload.abort()) {
console.log('aborted');
$('#uploadaudioform')[0].reset();
}}
This works fine only when the data is being uploaded, not after the upload succeeds or before the upload is triggred. In these conditions, this message shows up
Uncaught TypeError: Cannot call method 'abort' of undefined
I have even tried these ways while aborting:
if(myaudioupload!=='undefined' && myaudioupload.abort=='function'){
myaudioupload.abort();
console.log('aborted');
$('#uploadaudioform')[0].reset();
}
but this also does not work; the same error occurs.
So please help me how should i do this or if something is wrong in my code.
Thanks.
Change
myaudioupload!=='undefined'
to
typeof myaudioupload !== 'undefined'
I think myaudioupload.abort=='function' is not a correct way to check property type, use
typeof(myaudioupload.abort) == 'function' instead.