JQuery Validation not posting data to backend - javascript

I have something weird going on that I am trying to work out. I have a simple submitHandle that passes one bit of data to my PHP file
submitHandler: function (form) {
$.ajax({
type: "POST",
url: "form-process.php",
data: {
'customer': $("input[name='customer']:checked").val()
}
}).done(function (response) {
console.log(response)
}).fail(function (jqXHR, textStatus) {
console.log(textStatus)
});
return false;
}
If I output $("input[name='customer']:checked").val() I get the expected value of yes or no. Now in my PHP file, I am simply doing
echo json_encode($_POST["customer"]);
This seems to produce the error
Undefined index: customer
If I just check $_POST it returns an empty array.
Am I missing something here? Is there a reason this data isn't making it to the backend?

Try this method :
$.ajax({
method: "POST",
url: "form-process.php",
data: { customer: $("input[name='customer']:checked").val() }
}).done(function(response) {
console.log( "Data Saved: " + response);
}).error(function(error){
console.log(error)
});

You should use $("input[name='customer']:checked") ? true : false because if the input is not checked $("input[name='customer']:checked") will return null and then you will have null.val() which is not correct
data: {
customer: $("input[name='customer']:checked") ? true : false
}

Related

Ajax: Pass Model List to Controller

I have a view that takes a list of a model as the Model, so
#model List<Collections.Models.Status>
I want to pass this list as the data for an Ajax call, but I keep getting "System.Collections.Generic.List[Collections.Models.Status]" instead of the values in the model.
Here's the Ajax code:
$.ajax({
url: "/Home/Update",
data: JSON.stringify(#Model),
type: 'POST',
dataType: 'json',
success: function (responseJSON) {
if (responseJSON.message == 'success') {
alert('here');
}
},
error: function (error) {
showModal("Error: " + error.message);
}
});
Which translates in the debugger to:
$.ajax({
url: "/Home/Update",
data: JSON.stringify(System.Collections.Generic.List`1[Collections.Models.CollectionStatus]),
type: 'POST',
dataType: 'json',
success: function (responseJSON) {
if (responseJSON.message == 'success') {
alert('here');
}
},
error: function (error) {
showModal("Error: " + error.message);
}
});
How do I pass the actual values of the list instead of System.Collections.Generic.List[Collections.Models.Status]?
I've tried #Model.ToList(), #Html.Raw(Model), neither worked.
set contentType property to application/json.
and use below code to set data property
data: JSON.stringify({'your controllers parameter name': '#Model'})

jQuery AJAX POST method not working

I am trying to execute the AJAX operation. the call is working fine but the problem I am having is that I am getting an empty string as a response. There is no error in the console. all I get is an empty string. Even when I change the dataType to JSON, I still get the same response.
JavaScript Code:
$.ajax({
url: "data/saveCart.php",
method: "POST",
data: {
cartItem:item
},
dataType: "text",
success: function(data){
console.log(data);
}
});
PHP code:
if(isset($_POST['cartItem'])) {
echo "AJAX successful";
} else {
echo "AJAX failed";
}
It seems like it was caused by not stringifying your data.
var item = {
toothbrush: {
price: 1
}
};
$.ajax({
url: "data/saveCart.php",
method: "POST",
data: {
cartItem: JSON.stringify( item )
},
dataType: "text",
success: function(data){
console.log(data);
}
});

jQuery validator additional method not working as expected

I am using this jQuery validation plugin, http://jqueryvalidation.org/ And I am creating an addition method, as shown here.
jQuery.validator.addMethod('exists', function(value, element) {
$.ajax({
data: {username: value},
type: 'POST',
url: 'action/check/',
dataType: 'json',
success: function(data) {
if (data==true) {
console.log(data);
return true;
}
if (data==false) {
console.log(data);
return false;
}
}
})
}, 'This username is already in use');
My console is getting the proper data back from the check script and in my console I can see true and false etc. But what I do not understand is the validation flag seems to flag the input regardless of what the input is.
rules: {
password_confirm: {
equalTo: 'input[name=password]'
},
username: {
exists: true
}
}
I already have username chris in my database, so when I type chris into the username input I should get a flag for being a duplicate user, but regardless of what type I get the validation flag.
What am I missing
Your validation won't work because it is asynchronous(ajax request).
You can use the existing remote rule to do that, make sure your request is returning true/false as its result
rules: {
password_confirm: {
equalTo: 'input[name=password]'
},
username: {
remote: {
url: 'action/check/',
type: 'POST'
}
}
}
jQuery.validator.addMethod('exists', function(value, element) {
var result = false;
$.ajax({
data: {username: value},
type: 'POST',
url: 'action/check/',
dataType: 'json',
success: function(data) {
result = data; // make sure data returns bool value
}
});
return result;
}, 'This username is already in use');

How to transform $.post to $.ajax?

I have this $.post peace of code:
$.post("../admin-login",
{
dataName:JSON.stringify({
username:uname,
password:pass,
})
}, function(data,status){
console.log("Data:"+data);
answer = data;
}
);
and I wont to transform it to $.ajax. On the servlet side I am demanding request.getParamter("dataName") but I do not know how to write data: section in $.ajax so that I can get parameters like that(request.getParamter("dataName"))? Also, it seems to be problem with this type of code, I am asuming cause of async, that I cannot do this:
var answer="";
function(data,status){
console.log("Data:"+data);
answer = data;
}
And that answer is keeping empty(""), even though in console is written in deed "true" or "false" as my server answers. What is this about?
Thanks in advance.
I found out that problem is in the click() event. Ajax finishes when click() finishes, so I am not able to get data before event is done. What is bad in that is that I cannot fetch data because it is finished. Does anyone know how to solve this?
$.post("../admin-login",
{
dataName:JSON.stringify({
username:uname,
password:pass,
})
}, function(data,status){
console.log("Data:"+data);
answer = data;
}
);
becomes
function getResult(data) {
// do something with data
// you can result = data here
return data;
}
$.ajax({
url: "../admin-login",
type: 'post',
contentType: "application/x-www-form-urlencoded",
data: {
dataName:JSON.stringify({
username:uname,
password:pass,
})
},
success: function (data, status) {
getResult(data);
console.log(data);
console.log(status);
},
error: function (xhr, desc, err) {
console.log(xhr);
}
});
You need to see how the information os arriving to your servlet as query parameter or payload.
See this HttpServletRequest get JSON POST data
You could try structuring your AJAX request like the below:
var dataName = username:uname, password:pass;
$.ajax({
url: "../admin-login",
data: JSON.stringify(dataName),
type: "POST",
cache: false,
dataType: "json"
}).done(function(data, status) {
console.log("Data:"+data);
answer = data;
});

PHP not correctly returning JSON for an AJAX call

I have a PHP function that is supposed to return a JSON object to an AJAX call, but instead it is returning a string. Here is the PHP that I am calling from an AJAX call.
<?php
echo json_encode(array("error", 0, "Success!"));
?>
Here is the AJAX call.
$.ajax({
type: "POST",
url: "../api/login.php",
data: { id: username, password: password },
success: function(response) {
alert( "Data Saved: " + response );
$("#login_username").val("");
$("#login_password").val("");
}
});
When this function returns, I try to access response in the console, and this is what happens
response
> "["error",0,"Success!"]"
response[0]
> "["
If you are expecting an object then specify the dataType:json in the ajax settings. It will also ensure that if there are any invalid JSON being sent from the server, it gets erred out with parse error. Most probably you don't have a content-type (application/json; charset=utf-8) specified in your response header which lets jquery to determine the mime type itself, so specify the dataType ensure that you get an object or an error back(incase of invalid JSON).
$.ajax({
type: "POST",
dataType:'json'
url: "../api/login.php",
data: { id: username, password: password },
success: function(response) {
alert( "Data Saved: " + response );
$("#login_username").val("");
$("#login_password").val("");
}
});
Your implementation appears to be using jQuery, or some mock-up of jQuery. If it is not using jQuery, I will be happy to share more solutions to your problem.
Add dataType
$.ajax({
dataType: 'json',
type: "POST",
url: "../api/login.php",
data: { id: username, password: password },
success: function(response) {
alert( "Data Saved: " + response );
$("#login_username").val("");
$("#login_password").val("");
}
});
The problem is that, by default, jQuery expects a string.
var foo = "bar";
foo[1] === "a"; // true
Documentation: jQuery.ajax
add a param in your ajaxcall
$.ajax({
type: "POST",
url: "../api/login.php",
data: { id: username, password: password },
dataType: "json" //-< add this param.
success: function(response) {
alert( "Data Saved: " + response );
$("#login_username").val("");
$("#login_password").val("");
}
});
http://api.jquery.com/jQuery.post/

Categories