java script if statement not working? - javascript

On client side, I have JSon data send to server
myJson = {
request_type: 1,
list_empty: false,
data_list: []
};
send to server
$.ajax({
type: "POST",
url: self.serverURI,
data: self.gen_data(),
dataType: 'json',
success: function(result) {},
error: function(xhr, ajaxOptions, thrownError) {
console.log(xhr);
}
});
on the server
var m_bool = data.list_empty;
console.log("m_bool is printed: ", data.list_empty);
if (!m_bool) {
console.log("m_bool = false");
}
if (m_bool) {
console.log("m_bool = true");
}
The funny thing is server printed
m_bool = true
why if statements working?
I am using Node.js.
can anyone explain to me, thanks!

If you are using
dataType: 'json'
Please set
contentType: 'application/json'
in your jQuery ajax call, and JSON.stringify your data before you send it will arrive at the server as a parse-able javascript object.
As you are using NodeJS it will arrive as a Javascript object, with correct booleans, not string.
If you leave out the content type attribute things get messed up.

Your code is printing m_bool = true.
The reason for getting this printed is the list_empty: false would be received
as string in the server side.
var s = "false";
if(!s) {
console.log("S is false");}
else {
console.log("S is true");
}
result of the above snippet is always "S is true".
Ensure that you are receiving it as JSON object on the server side, add the necessary headers contentType: 'application/json'

In this case javascript checks that 'm_bool' should be truthy.
if(m_bool)
But if you want to check boolean value you should write like:
if(m_bool === true)
This will only satisfy boolean true case.

Related

Ajax and PHP, post request not working

So I am trying to post some some data from one PHP file to another PHP file using jquery/ajax. The following code shows a function which takes takes data from a specific div that is clicked on, and I attempt to make an ajax post request to the PHP file I want to send to.
$(function (){
$(".commit").on('click',function(){
const sha_id = $(this).data("sha");
const sha_obj = JSON.stringify({"sha": sha_id});
$.ajax({
url:'commitInfo.php',
type:'POST',
data: sha_obj,
dataType: 'application/json',
success:function(response){
console.log(response);
window.location.replace("commitInfo");
},
error: function (resp, xhr, ajaxOptions, thrownError) {
console.log(resp);
}
});
});
});
Then on inside the other php file 'commitInfo.php' I attempt to grab/print the data using the following code:
$sha_data = $_POST['sha'];
echo $sha_data;
print_r($_POST);
However, nothing works. I do not get a printout, and the $_POST array is empty. Could it be because I am changing the page view to the commitInfo.php page on click and it is going to the page before the data is being posted? (some weird aync issue?). Or something else? I have tried multiple variations of everything yet nothing truly works. I have tried using 'method' instead of 'type', I have tried sending dataType 'text' instead of 'json'. I really don't know what the issue is.
Also I am running my apache server on my local mac with 'sudo apachectl start' and running it in the browser as 'http://localhost/kanopy/kanopy.php' && 'http://localhost/kanopy/commitInfo.php'.
Also, when I send it as dataType 'text' the success function runs, but I recieve NO data. When I send it as dataType 'json' it errors. Have no idea why.
If anyone can help, it would be greaat!
You don't need to JSON.stringify, you need to pass data as a JSON object:
$(function() {
$(".commit").on('click', function() {
const sha_id = $(this).data("sha");
const sha_obj = {
"sha": sha_id
};
$.ajax({
url: 'commitInfo.php',
type: 'POST',
data: sha_obj,
dataType: 'json',
success: function(response) {
console.log(response);
},
error: function(resp, xhr, ajaxOptions, thrownError) {
console.log(resp);
}
});
});
});
And on commitInfo.php, you have to echo string on json format
=====================================
If you want to redirect to commitInfo.php you can just:
$(".commit").on('click',function(){
const sha_id = $(this).data("sha");
window.location.replace("commitInfo.php?sha=" + sha_id );
});

Form post warning message after upgrading jquery

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.

JQuery Ajax not sending data to PHP

myscript.js below is outputing:
[{"orcamento":"10","atual":"20","desvio":"","data":"2015-01-01","nome_conta":"BBB","nome_categoria":"abc","nome_entidade":"def"}]
myscript.js:
if (addList.length) {
$.ajax($.extend({}, ajaxObj, {
data: { "addList": JSON.stringify(addList) },
success: function (rows) {
$grid.pqGrid("commit", { type: 'add', rows: rows });
},
complete: function () {
$grid.pqGrid("hideLoading");
$grid.pqGrid("rollback", { type: 'add' });
$('#consola').text(JSON.stringify(addList));
}
}));
}
The JSON data above has to be sent to my script.php below:
if( isset($_POST["addList"]))
{
$addList = json_decode($_POST["addList"], true);
var_dump ($addList);
echo "test";
exit();
}
Although the data is correct and myscript.php is being called it isn't returning anything. I get:
NULLtest
I tried using GET, instead of POST but the result is the same, what is wrong with the code above?
EDIT:
Here's the ajaxObj used in the ajax request:
var ajaxObj = {
dataType: "json",
url:"../myscript.php",
type: "POST",
async: true,
beforeSend: function (jqXHR, settings) {
$grid.pqGrid("showLoading");
}
};
From the PHP Docs on json_decode:
NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit.
So it is most likely that there is some error in your JSON data that is preventing json_decode from parsing it correctly, I've ran that snippet through jsonlint and it does say that it's valid JSON, but it's worth checking a larger sample of the data you send to the server for inconsistencies.
Other than that, is there any reason that you are calling JSON.stringify on the data object prior to sending to the server? I would try just sending the object itself as the data parameter of your AJAX call like so:
$.ajax($.extend({}, ajaxObj, {
data: { "addList": addList },
success: function (rows) {
$grid.pqGrid("commit", { type: 'add', rows: rows });
},
complete: function () {
$grid.pqGrid("hideLoading");
$grid.pqGrid("rollback", { type: 'add' });
$('#consola').text(JSON.stringify(addList));
}
}));
And see if that helps:
EDIT
I should have noticed in my original answer, you will not need to call json_decode on your posted data, jQuery encodes the data as post parameters correctly for you; It should be accessible within your PHP script as an associative array, try replacing your current var_dump statement in your PHP var_dump($_POST['addList'][0]['orcamento']); and you should be good to go.
First of all, be sure you are posting to a php file, use firebug or similar tools to track your script..
I don't see the part you defined the target PHP file on your javascript file..
A regular javascript code can look like this :
jQuery.ajax({
type : "post",
dataType : "json",
url : 'target.php',
data : {foo:bar },
success: function(response) {
// do something with response...
}
});
If you see that you are posting to the right php file the right parameters on firebug, try to use $_REQUEST if $_POST not working..
Firebug will show you the response of PHP file.. so do a print_r($_REQUEST['addList']) to see what is going on...

Getting Uncaught SyntaxError: Unexpected token : when reading jsonp response

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

jQuery AJAX and handling different dataTypes

I'm using ASP.Net MVC, but this applies to any framework.
I'm making an Ajax call to my server, which most of the time returns plain old HTML, however if there is an error, I'd like it to return a JSON object with a status message (and a few other things). There doesn't appear to be a way for the dataType option in the jQuery call to handle this well. By default it seems to parse everything as html, leading to a <div> being populated with "{ status: 'error', message: 'something bad happened'}".
[Edit] Ignoring the dataType object and letting jQuery figure out doesn't work either. It views the type of the result as a string and treats it as HTML.
One solution I came up with is to attempt to parse the result object as JSON. If that works we know it's a JSON object. If it throws an exception, it's HTML:
$.ajax({
data: {},
success: function(data, textStatus) {
try {
var errorObj = JSON.parse(data);
handleError(errorObj);
} catch(ex) {
$('#results').html(data);
}
},
dataType: 'html', // sometimes it is 'json' :-/
url: '/home/AjaxTest',
type: 'POST'
});
However, using an Exception in that way strikes me as pretty bad design (and unintuitive to say the least). Is there a better way? I thought of wrapping the entire response in a JSON object, but in this circumstance, I don't think that's an option.
Here's the solution that I got from Steve Willcock:
// ASP.NET MVC Action:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AjaxTest(int magic) {
try {
var someVal = GetValue();
return PartialView("DataPage", someVal);
} catch (Exception ex) {
this.HttpContext.Response.StatusCode = 500;
return Json(new { status = "Error", message = ex.Message });
}
}
// jQuery call:
$.ajax({
data: {},
success: function(data, textStatus) {
$('#results').html(data);
},
error: function() {
var errorObj = JSON.parse(XMLHttpRequest.responseText);
handleError(errorObj);
},
dataType: 'html',
url: '/home/AjaxTest',
type: 'POST'
});
For your JSON errors you could return a 500 status code from the server rather than a 200. Then the jquery client code can use the error: handler on the $.ajax function for error handling. On a 500 response you can parse the JSON error object from the responseText, on a 200 response you can just bung your HTML in a div as normal.
While Steve's idea is a good one, I'm adding this in for completeness.
It appears that if you specify a dataType of json but return HTML, jQuery handles it fine.
I tested this theory with the following code:
if($_GET['type'] == 'json') {
header('Content-type: application/json');
print '{"test":"hi"}';
exit;
} else {
header('Content-type: text/html');
print '<html><body><b>Test</b></body></html>';
exit;
}
The $_GET['type'] is just so I can control what to return while testing. In your situation you'd return one or the other depending on whether things went right or wrong. Past that, with this jQuery code:
$.ajax({
url: 'php.php?type=html', // return HTML in this test
dataType: 'json',
success: function(d) {
console.log(typeof d); // 'xml'
}
});
Even though we specified JSON as the dataType, jQuery (1.3.2) figures out that its not that.
$.ajax({
url: 'php.php?type=json',
dataType: 'json',
success: function(d) {
console.log(typeof d); // 'object'
}
});
So you could take advantage of this (as far as I know) undocumented behavior to do what you want.
But why not return only JSON regardless of the status (success or error) on the POST and the use a GET to display the results? It seems like a better approach if you ask me.
Or you could always return a JSON response, and have one parameter as the HTML content.
Something like:
{
"success" : true,
"errormessage" : "",
"html" : "<div>blah</div>",
}
I think you'd only have to escape double quotes in the html value, and the json parser would undo that for you.
I ran into this exact same issue with MVC/Ajax/JQuery and wanting to use multiple dataTypes (JSON and HTML). I have a AJAX request to uses an HTML dataType to return the data, but I attempt convert the data that comes back from the ajax request to a JSON object. I have a function like this that I call from my success callback:
_tryParseJson: function (data) {
var jsonObject;
try {
jsonObject = jQuery.parseJSON(data);
}
catch (err) {
}
return jsonObject;
}
I then assume that if the jsonObject and errorMessage property exist, that an error occured, otherwise an error did not occur.
I accomplished this by using the ajax success and error callbacks only. This way I can have mixed strings and json objects responses from the server.
Below I'm prepared to accept json, but if I get a status of "parsererror" (meaning jquery couldn't parse the incoming code as json since that's what I was expecting), but it got a request status of "OK" (200), then I handle the response as a string. Any thing other than a "parsererror" and "OK", I handle as an error.
$.ajax({
dataType: 'json',
url: '/ajax/test',
success: function (resp) {
// your response json object, see if status was set to error
if (resp.status == 'error') {
// log the detail error for the dev, and show the user a fail
console.log(resp);
$('#results').html('error occurred');
}
// you could handle other cases here
// or use a switch statement on the status value
},
error: function(request, status, error) {
// if json parse error and a 200 response, we expect this is our string
if(status == "parsererror" && request.statusText == "OK") {
$('#results').html(request.responseText);
} else {
// again an error, but now more detailed and not a parser error
// and we'll log for dev and show the user a fail
console.log(status + ": " + error.message);
$('#results').html('error occurred');
}
}
});

Categories