I am trying to parse json response. The JSON response is coming in responseText property
First of all i am getting response from Json as follows:
{"Success":false,"Error":true,"ErrorType":1,"ModelErrors":{"Name":"\u0027Name\u0027 must not be empty.","Owner":"\u0027Owner\u0027 must not be empty.","Email":"\u0027Email\u0027 must not be empty.","Password":"\u0027Password\u0027 must not be empty.","Size":"Please provide a valid Number"}}
when i do console.log(response.responseText) i get the above output on console.
Now I am catching this response in this function. Everything work fine in success but when error block executes in case of error I get ModelErrors property undefined. Here is my function
$("form").on('submit', function () {
var form = $('.form');
var url = form.attr('action');
var formData = form.serialize();
$.ajax({
type: 'POST',
url: url,
dataType: 'json',
data: formData,
success: function (response) {
if (response.Success==true) {
console.log(response.Success);
showMsg(response.Message);
//alert(response.Message);
}
//alert(data);
},
error: function (response) {
console.log(response.responseText);
if (response.responseText.Error === true)
{
var modelErrors = response.responseText.ModelErrors;
console.log(modelErrors);
console.log("Check "+modelErrors);
}
},
cache: false
});
});
I tried different solutions but i could not figure out where i am doing wrong. Please help me in this regard. Thanks
You can parse the JSON
var json='{"Success":false,"Error":true,"ErrorType":1,"ModelErrors":{"Name":"\u0027Name\u0027 must not be empty.","Owner":"\u0027Owner\u0027 must not be empty.","Email":"\u0027Email\u0027 must not be empty.","Password":"\u0027Password\u0027 must not be empty.","Size":"Please provide a valid Number"}}';
var tmp=JSON.parse(json);
console.log(tmp.ModelErrors);
Related
Hello I am not good with ajax.I want to check my login info and return either 'success' or 'fail'.Buy my ajax seems to have an error.
var user = $('.username').value();
var pass = $('.password').value();
$.ajax({
type : 'POST',
url : 'login_check.php',
data : {
'username': user,
'password': pass
},
beforeSend: function() {
$("#Loading").show();
},
success : function(response) {
if(response=="success" && response!=="fail") {
$('.status').html("Success! Now logging in ......");
setTimeout(' window.location.href = "index.php"; ',4000);
} else {
$('#Loading i').hide();
$('.status').html("Login fail! Please use correct credentials....");
setTimeout(' window.location.href = "login.php"; ',4000);
}
}
});
Can anyone points me out?
The reason you are getting error is because your javascript is getting break(giving error) at $('.username').value(); as there is no value() function. If you open console you get this error. So because of this rest of script is not working. So change $('.username').value(); to this $('.username').val(); and same for the var pass = $('.password').value(); change to var pass = $('.password').val(); and also you don't need if condition as mention in comment. Your final code will be something like this.
var user = $('.username').val();
var pass = $('.password').val();
$.ajax({
type: 'POST',
url: //some url
data: {
'username': user,
'password': pass,
},
beforeSend: function() {
//some code
},
success: function(response) {
// some code which you want to excute on success of api
},
error: function(xhr, status, error) {
// some code which you want to excute on failure of api
}
});
I dont have the whole code for your app but when it come to your ajax request your code should look like this , for a more accurate answer please show the error that you are getting
var user = $('.username').val();
var pass = $('.password').val();
$.ajax({
type : 'POST',
url : 'login_check.php',
data : {
'username':user,
'password':pass,
},
beforeSend: function()
{
$("#Loading").show();
},
success : function(response)
{
$('.status').html("Success! Now logging in ......");
setTimeout(()=>{ window.location.href = "index.php"; },4000);
},
error: function(xhr, status, error) {
$('#Loading i').hide();
$('.status').html("Login fail! Please use correct credentials....");
setTimeout(()=>{ window.location.href = "login.php"},4000);
}
});
Your response needs to be a PHP echo that returns a string with a value of either ”success” or ”fail”.
Your PHP response after successful login:
echo(‘success’);
Your PHP response after failed login:
echo(‘fail’);
I need to validate, on server side, if a person with a given registration number is already on the database. If this person is already registered, then I proceed with the program flow normally. But, if the number is not already registered, then I'd like to show a confirmation dialog asking if the operator wants to register a new person with the number entered and, if the operator answers yes, then the person will be registered with the number informed on the form on it's submission.
I've tried
Server side(PHP):
if (!$exists_person) {
$resp['success'] = false;
$resp['msg'] = 'Do you want to register a new person?';
echo json_encode($resp);
}
Client side:
function submit(){
var data = $('#myForm').serialize();
$.ajax({
type: 'POST'
,dataType: 'json'
,url: 'myPHP.php'
,async: 'true'
,data: data
,error: function(response){
alert('response');
}
});
return false;
}
I can't even see the alert, that's where I wanted to put my confirmation dialog, with the message written on server side. Other problem, how do I resubmit the entire form appended with the operator's answer, so the server can check if the answer was yes to register this new person?
EDIT
I was able to solve the problem this way:
Server side(PHP):
$person = find($_POST['regNo']);
if ($_POST['register_new'] === 'false' && !$person) {
$resp['exists'] = false;
$resp['msg'] = 'Do you want to register a new person?';
die(json_encode($resp)); //send response to AJAX request on the client side
} else if ($_POST['register_new'] === 'true' && !$person) {
//register new person
$person = find($_POST['regNo']);
}
if($person){
//proceed normal program flow
}
Client side:
function submit(e) {
e.preventDefault();
var data = $('#myForm').serialize();
var ajax1 = $.ajax({
type: 'POST'
, dataType: 'json'
, async: 'true'
, url: 'myPHP.php'
, data: data
, success: function (response) {
if (!response.exists && confirm(response.msg)) {
document.getElementById('register_new').value = 'true'; //hidden input
dados = $('#myForm').serialize(); //reserialize with new data
var ajax2 = $.ajax({
type: 'POST'
, dataType: 'json'
, async: 'true'
, url: 'myPHP.php'
, data: data
, success: function () {
document.getElementById('register_new').value = 'false';
$('#myForm').unbind('submit').submit();
}
});
} else if (response.success) {
alert(response.msg);
$('#myForm').unbind('submit').submit();
}
}
});
}
There doesn't appear to be anything wrong with your PHP.
The problem is (1) You are doing the alert inside of an error callback, and your request isn't failing, so you don't see the alert. (2) You are alerting the string 'response' instead of the variable response.
It is also worth noting that you should be using the .done() and .fail() promise methods (http://api.jquery.com/jquery.ajax/#jqXHR).
Here is the fixed JS:
function submit() {
var data = $('#myForm').serialize();
// Same as before, with the error callback removed
var myAjaxRequest = $.ajax({
type: 'POST',
dataType: 'json',
url: 'myPHP.php',
async: 'true',
data: data
});
// The request was successful (200)
myAjaxRequest.done(function(data, textStatus, jqXHR) {
// The data variable will contain your JSON from the server
console.log(data);
// Use a confirmation dialog to ask the user your question
// sent from the server
if (confirm(data.msg)) {
// Perform another AJAX request
}
});
// The request failed (40X)
myAjaxRequest.fail(function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
});
return false;
}
Also, you are setting a 'status' in PHP and checking that in the JS (I presume). What you want to be doing is setting a HTTP status code from the server, as below:
if (!$exists_person)
{
$resp['msg'] = 'Do you want to register a new person?';
// 400 - Bad Request
http_response_code(400);
echo json_enconde($resp);
}
Then, jQuery will determine whether the request failed based on the status code you respond with. 200 is a successful request, and 400 numbers are fail.
Check out this page for a full list: https://httpstatuses.com/
Okay so this is a two part question; I'll try my best to answer both parts:
Part 1: How to detect if success is false and trigger the confirmation popup?
In jQuery.ajax the error handler is triggered based on response code. This is probably not what you want. You can use your success handler and test the value res.success to see if it's true or false. It would be something along the lines of:
function submit(e) {
e.preventDefault();
var data = $('#myForm').serialize();
$.ajax({
type: 'POST',
dataType: 'json',
url: 'myPHP.php',
async: 'true',
data: data
}).done(function(res) {
if (!res.success) {
alert(res.msg);
}
});
}
Part 2: How do I resubmit with a confirmation?
Working off of our previous code we will make some changes that allow for submit() to be passed an argument registerNew. If registerNew is true we will pass it as a param to the ajax handler in the PHP so it knows we want to register a new person. The Javascript will look something like this:
function submit(e, registerNew) {
if (e) e.preventDefault();
var data = $('#myForm').serialize();
var ajax_options = {
type: 'POST',
dataType: 'json',
url: 'myPHP.php',
async: 'true',
data: data
};
ajax_options.data.register_new = !!registerNew;
$.ajax(ajax_options).done(function(res) {
if (!res.success && confirm(res.msg)) {
submit(null, true);
}
});
}
As you can see here, we are passing a new register_new param in the data in our ajax options. Now we need to detect this on the PHP side, which is easy enough and looks like this (this goes in your php ajax handler):
if ($_POST["register_new"]) {
// new user registration code goes here
} else {
// your existing ajax handler code
}
Add confirm inside submit function
function submit(){
var data = $('#myForm').serialize();
if (confirm('Are you ready?')) {
$.ajax({
type: 'POST'
,dataType: 'json'
,url: 'myPHP.php'
,async: 'true'
,data: data
,error: function(response){
alert('response');
}
});
}
return false;
}
I have upgraded to jquery 1.10.2. I am using jquery migrate and I am having the warning message "jQuery.parseJSON requires a valid JSON string"
I have not understood how I can correct that. Can anyone help me out with the best solution of how I can remove the warning message
The javascript is as follows:
function Search() {
$.ajax({
cache: false,
contentType: "application/json; charset=utf-8",
dataType: "html",
url: "#Url.Action("Search")",
data: JSON.stringify({myModel: $("#DateFrom").val()}),
success: function (data)
{
$("#NewDiv").html(data);
},
error: function (request, status, error)
{
DisplayError(ParseErrorFromResponse(request.responseText, "Unknown error"), true);
}
});
}
In the Controller:
public PartialViewResult Search(myModel myModel)
{
return PartialView("SearchResult", myModel);
}
ParseErrorFromResponse:
Function ParseErrorFromResponse(responseText, defaultError)
{
var text = responseText.replace("<title>", "TitleStart");
var startIndex = text.indexOf("TitleStart");
var endIndex = text.indexOf("TitleEnd");
return (startIndex == -1 || endIndex == -1) ? defaultError : text.substring(startIndex + 10, endIndex);
}
You need to send your data as JSON.
Where you have data: $("#DateFrom").val(), replace it with data: JSON.stringify({$("#DateFrom").val()}).
EDIT: You may need to send it as JSON.stringify({(myModel: $("#DateFrom").val()}).
The error may be related to "" or false values that used to convert to null in versions of jQuery prior to 1.9.0 per THIS PAGE
Here it the relevant excerpt including the suggested solution:
JQMIGRATE: jQuery.parseJSON requires a valid JSON string
Cause: Before jQuery 1.9.0, the $.parseJSON() method allowed some
invalid JSON strings and returned null as a result without throwing an
error. This put it at odds with the JSON.parse() method. The two
methods are aligned as of 1.9.0 and values such as an empty string are
properly not considered valid by $.parseJSON().
Solution: If you want to consider values such as "" or false
successful and treat them as null, check for them before calling
$.parseJSON(). Since falsy values such as an empty string were
previously returned as a null without complaint, this code will
suffice in most cases:
var json = $.parseJSON(jsonString || "null");
If your own code is not
calling $.parseJSON() directly, it is probably using AJAX to retrieve
a JSON value from a server that is returning an empty string in the
content body rather than a valid JSON response such as null or {}. If
it isn't possible to correct the invalid JSON in the server response,
you can retrieve the response as text:
$.ajax({
url: "...",
dataType: "text",
success: function( text ) {
var json = text? $.parseJSON(text) : null;
...
}
});
Remove content-type attribute and do like this:
function Search() {
$.ajax({
cache: false,
url: "#Url.Action("Search","ControllerName")",
dataType:"html",
data:
{
myModel: $("#DateFrom").val()
},
success: function (data)
{
$("#NewDiv").html(data);
},
error: function (request, status, error)
{
DisplayError(ParseErrorFromResponse(request.responseText, "Unknown error"), true);
}
});
}
and in action:
public PartialViewResult Search(string myModel)
{
return PartialView("SearchResult", myModel);
}
I think it's because you're missing double quotes around key myModel in line
...
data: JSON.stringify({myModel: $("#DateFrom").val()},
...
and not because of jquery version upgrade.try using
data: JSON.stringify({"myModel": $("#DateFrom").val()},
Try like this.. You have to return Json as result from your Search().
public JsonResult Search(myModel myModel)
{
return Json(result);
}
and also in you Script, try like this..
$.ajax({
type:"POST"
cache: false,
contentType: "application/json; charset=utf-8",
url: "#Url.Action("Search","ControllerName")",
dataType: "json",
data: JSON.stringify({"myModel": $("#DateFrom").val()}),
success: function (data)
{
$("#NewDiv").html(data);
}
});
Also check $("#DateFrom").val() is having correct value and put an
alert(data)
in success and check the returned data.
I have updated the url.
I am working on a piece of code where the user clicks on a button to make a call and the status of the call is displayed to him/her.
Everything is working fine and the calls are being made too, but the server which sends the json response is on another domain and I have no control over its response. I therefore used jsonp to get the response, but no matter what i did, i keep getting the error of Uncaught SyntaxError: Unexpected token.
I am attaching my code. please help as this is a live project and I am badly stuck in it. I need a response to be alerted with the message received by the server. the message received by the server in case of success is {"success": {"status": "success", "message": "Call successfully placed"}} and in case of error is {"error": {"message": "Invalid API Key"}}. I just need to display the message part.
my code:
function makecall() {
document.getElementById('<%=click2call_submitbtn.ClientID%>').disabled = true;
var agentNum = document.getElementById('<%=lblCallFrom.ClientID%>').innerHTML;
var custNum = "+91";
custNum = custNum + document.getElementById('<%=txtNotoCall.ClientID%>').value;
document.getElementById('<%=lblCallStatus.ClientID%>').innerHTML = "Calling...";
if (validatePhone(agentNum) && validatePhone(custNum)) {
$.ajax({
url: 'http://www.knowlarity.com/vr/api/click2call/?api_key=9e69eab0-1ec7-11e3-866c-16829204aaa4&agent_number=agent_number_variable&phone_number=Caller_number_variable&sr_number=%2B918881692001&response_format=json'.replace('Caller_number_variable', custNum.replace('+', '%2B')).replace('agent_number_variable', agentNum.replace('+', '%2B')),
type: 'GET',
cache: false,
dataType: 'jsonp',
success: function (res) {
alert(JSON.stringify(res));
},
error: function (res) {
alert(JSON.stringify(res));
}
});
} else {
document.getElementById('<%=lblCallStatus.ClientID%>').innerHTML = "Num. should be a valid 10 digit mobile no.";
document.getElementById('<%=click2call_submitbtn.ClientID%>').disabled = false;
}
}
Try using this as an absolute minimum where you can pass in valid hard wired values for the numbers:
var url = 'http://ip.jsontest.com/ ';
$.ajax({
url: url,
cache: false,
dataType: 'jsonp',
success: function (res) {
if (res != undefined) console.log(res);
},
error: function (res) {
if (res != undefined) console.log(res);
}
});
I got some problem while posting JSON data into MVC 4 controller.
Below method is working fine in Firefox but unfortunately failed in IE 9
The JavaScript :
var newCustomer = {
CustName: $("#CustName").val(),
CustLocalName: $("#CustLocalName").val(),
CustNumber: $("#CustNumber").val(),
CountryID: $("#SelectCountry").val(),
City: $("#City").val()
};
$.ajax({
url: '#Url.Content("~/CustomerHeader/CreateCustomerHeader")',
cache: false,
type: "POST",
dataType: "json",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(newCustomer),
success: function (mydata) {
$("#message").html("Success");
},
error: function () {
$("#message").html("Save failed");
}
});
and this is my controller :
public JsonResult CreateCustomerHeader(CustomerHeader record)
{
try
{
if (!ModelState.IsValid)
{
return Json(new { Result = "ERROR", Message = "Form is not valid! Please correct it and try again." });
}
RepositoryHeader.Update(record);
return Json(new { Result = "OK", Record = record});
}
catch (Exception ex)
{
return Json(new { Result = "ERROR", Message = ex.Message });
}
}
the "data" variable as in public JsonResult CreateCustomerHeader(CustomerHeader **data**) is getting NULL but while using FireFox it holds the correct value.
UPDATE : New method trying using $.post
function CreateNewCustomer(newCustomer) {
$.post("/CustomerHeader/CreateCustomerHeader",
newCustomer,
function (response, status, jqxhr) {
console.log(response.toString())
});
}
Based off the bit that you've shown, this is a simplified variation that may work more consistently, using jQuery.post() (http://api.jquery.com/jQuery.post/):
var data = {
CustName: $("#CustName").val(),
CustLocalName: $("#CustLocalName").val(),
CustNumber: $("#CustNumber").val(),
CountryID: $("#SelectCountry").val(),
City: $("#City").val()
};
$.post({
'#Url.Action("CreateCustomerHeader", "CustomerHeader")',
data,
function(response, status, jqxhr){
// do something with the response data
}).success(function () {
$("#message").html("Success");
}).error(function () {
$("#message").html("Save failed");
});
$.post() uses $.ajax as it's base, but abstracts some of the details away. For instance, $.post calls are not cached, so you don't need to set the cache state (and setting it is ignored if you do). Using a simple JavaScript object lets jQuery decide how to serialize the POST variables; when using this format, I rarely have issues with the model binder not being able to properly bind to my .NET classes.
response is whatever you send back from the controller; in your case, a JSON object. status is a simple text value like success or error, and jqxhr is a jQuery XMLHttpRequest object, which you could use to get some more information about the request, but I rarely find a need for it.
first of all I would like to apologize #Tieson.T for not providing details on JavaScript section of the view. The problem is actually caused by $('#addCustomerHeaderModal').modal('hide') that occurred just after ajax call.
The full script :
try{ ..
var newCustomer =
{
CustName: $("#CustName").val(),
CustLocalName: $("#CustLocalName").val(),
CustNumber: $("#CustNumber").val(),
CountryID: $("#SelectCountry").val(),
City: $("#City").val()
};
$.ajax({
url: '/CustomerHeader/CreateCustomerHeader',
cache: false,
type: "POST",
dataType: "json",
data: JSON.stringify(newCustomer),
contentType: "application/json; charset=utf-8",
success: function (mydata) {
$("#message").html("Success");
},
error: function () {
$("#message").html("Save failed");
}
});
}
catch(Error) {
console.log(Error.toString());
}
//$('#addCustomerHeaderModal').modal('hide')//THIS is the part that causing controller cannot retrieve the data but happened only with IE!
I have commented $('#addCustomerHeaderModal').modal('hide') and now the value received by controller is no more NULL with IE. Don't know why modal-hide event behave like this with IE9.
Thanks for all the efforts in solving my problem guys :-)