I'm trying to break/return false if a $.post() response is null, by doing so:
....
$('#order_list li > div').remove(); // is to remove `no_data` or `search_box` when clicking on the next `li`
$.post('do.php', { OP: "news_search", category: cat_id },
function(data_response){
console.log(data_response); //outputs null if nothing retrieved, or data if otherwise
if(data_response==null) //stop code if the response is null
{
alert('if works');
$(this).append(no_data).show('slow');
return false; // doesn't do the trick
}
}, "json");
//if not null, continue with this
if( ! $('.search_box').exists())
{
$(this).append(search_box).show('slow');
}
....
But as you could read, my code doesn't do the trick. Any ideas?
UPDATE
the if(data_response==null) works, it's the return false that doesn't do its job
The A in AJAX is for Asynchronous.
When you get to the point where you want to check, it has already executed.
First you run this code:
$.post('do.php', { OP: "news_search", category: cat_id }, callback, "json");
This issues an XmlHttpRequest to the server. I intentionally wrote only callback, because the function is just passed as a parameter. It will only run when the server responded. By that time, the other parts of your code have already run.
$.post() - call to the server
the rest of your code
when the server responded, your callback
$.post('do.php', { OP: "news_search", category: cat_id },
function(data_response){
console.log(data_response);
if(data_response)
{
$(this).append(no_data).show('slow');
// return false; NOT NEEDED
} else {
// below condition should remain here, not outside of Ajax
if( ! $('.search_box').exists()){
$(this).append(search_box).show('slow');
}
}
}, "json");
People usually verify doing the following:
if (foo == null) {
foo = "Joe";
}
When what they really mean is
if (!foo) {
foo = "Joe";
}
Its because null is an object and == does type coercion.
More info in this article: JavaScript undefined vs. null
Related
hey guys i have this code here:
$('#internet').click(function(e){
e.preventDefault();
$.ajax({
url: "ajax/sessionset.php",
success: function (data){
if (data == 1){
$.ajax({
type: "POST",
//add variables
url: "ajax/loggedin.php",
success: function(data2){
//history.pushState({"internet.php?view=internetlog");
$('#internetlog').html(data2);
}
});
}
else if(data===0){
alert("suka");
}
}
});
});
The sessionset.php returns a value of either 1 or 0, depending if the session is currently going on or not.
Problem here is the link $('#internet')
returns the url loggedin.php when the data value is 1.
However if the data value is 0, nothing happens, since the e.preventDefault(); prevents any events.
Already checked on firebug that it either returns values of 1 or 0, I dont understand why the alert is not firing off when the value returned is 0...
edit: just checked the sessionset.php in a separate window instead of firebug
<?php
session_start();
if (!empty($_SESSION['origuserip'] && $_SESSION['loggedin'])){
$switch = "1";
}
else {
$switch = "0";
}
echo $switch;
the return value of 1 is 1 however if !empty is false it returns
Notice: Undefined index: origuserip in ajax\sessionset.php on line 4
0
SOLUTION:
Guess the simplest way is just the best way -_-
else {
("suka");
}
The scripts return value is probably a string, because you didn't specify the return type of your AJAX call.
You should validate like this: data==="1" and data==="0". Which checks for identity, as long as you definitely return strings.
data==1 is always true, if it's set and not null.
Regarding the other problem:
Make sure your $_SESSION variables are set properly when you check their indexes and separate the empty() checks. For example like this:
if (!empty($_SESSION['origuserip']) && !empty($_SESSION['loggedin'])){
$switch = "1";
}
else {
$switch = "0";
}
echo $switch;
I'm trying my best to create a website.
I need to create an IF-ELSE in ajax. It basically calls the content of an input called "greeting" and aims at writing "YES" if the user inserts a specific text and "NO" otherwise.
jQuery(document).ready(function () {
var greeting = jQuery("#greeting").val();
jQuery("#push-me").click(function () {
jQuery.ajax({
type: 'POST',
url: 'http://www.boatsandbeats.com/wordpress/wp-admin/admin-ajax.php',
data: {
action: 'myAjax',
greeting: jQuery("#greeting").val(),
},
success: function (data, textStatus, XMLHttpRequest) {
if (data == "XYZ") == 0 {
jQuery("#test-div").html('');
jQuery("#test-div").append("YES");
} else {
jQuery("#test-div").html('');
jQuery("#test-div").append("NOPE");
}
},
error: function (MLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
});
While the rest of the code works just fine, it does not recognize the IF and takes everything as if it were true (therefore, printing "YES").
Can anybody be so kind and explain this to me?
it is not working because your if statement is wrong
if (data == "XYZ") == 0 {
should be
if (data.greeting == "XYZ") {
}
Step 1: check if your ajax actually returns something.
...//add the following line
success: function (data, textStatus, XMLHttpRequest) {
console.log(data);
alert("Data logged." + data);
...
Step 2: what do you want to test?
You want to know if data (the ajax return) is a string and that string is having the value "XYZ"?
//change
if (data == "XYZ") == 0
//to
if (data === "XYZ")
Note the triple === it's not the same as ==. The difference is that === will check if the variables have the same value and the same type.
In addition, in Javascrip can compare string similar to your style like using localeCompare():
if (data.localeCompare("XYZ") === 0)
/* strA.localeCompare(strB); Returns:
0: exact match
-1: strA < strB
1: strB > strA
*/
UPDATE:
Assuming your php function is as the following:
function myAjax()
{
$greeting = $_POST['greeting'];
if (isset($_POST['greeting']))
$greeting = $_POST['greeting'];
$results = "<h2>".$greeting."</h2>";
die($results);
}
This is what's going to happen.
{
//$greeting is being assigned a value from POST greetings, // in post is empty then $greeting will be empty as well.
$greeting = $_POST['greeting'];
//You are validating POST greeting, although you already captured it's value and put it in $greeting, so why not using $greeting here instead?
if (isset($_POST['greeting']))// this if has no {} so ONLY the first line after will be included in this IF condition.
$greeting = $_POST['greeting'];
// this line will be exectue no matter what, so the value of $greeting will be entered into a string enclosed with <h2> tags. if POST greeting is empty, then $greeting will be empty of course.
$results = "<h2>" . $greeting . "</h2>";
//the variable $result now has "<h2></h2>" as it's value if $greeting is empty.
die($results); //echoing $result, or
}
So, since you have confirmed that you are receiving "" as a value for data variable returned from AJAX. Why are you comparing it to XYZ in your condition?
In your JS you are assigning "#greeting").val() to a variable greeting, then you use that variable as an array attribute for your ajax{data{greeting:jQuery("#greeting").val() }}
var greeting = jQuery("#greeting").val();// what is the use of this line?
Enclose your object attribute with "" e.g. "greeting".
data: {
"action": 'myAjax',
"greeting": jQuery("#greeting").val(),// what is the value of "#greeting").val()?
},
first of all you need to check data will exactly print XYZ or print [Object object]
if [Object object] then you need to check data.d=="XYZ"
in success function first parse then compare like this
var response=$.parseJSON(data);
if(response.field=="XYZ")
{
jQuery("#test-div").html('');
jQuery("#test-div").append("YES");
}
else
{
jQuery("#test-div").html('');
jQuery("#test-div").append("NOPE");
}
IF condition system is looks wrong,
if (data == "XYZ") == 0
You should use only, no need == 0
if (data == "XYZ"){
//.... code here
}
OR If ajax response in json
if (data.key == "XYZ"){
//.... code here
}
Heyho,
I got a function to get cookies and it works fine (except the if-part in getCookies()):
function getCookies(domain, name, callback) {
chrome.cookies.get({"url": domain, "name": name}, function(cookie) {
if(callback) {
callback(cookie.value);
}
});
}
//USER ID
getCookies("http://free-way.me", "uid", function(id) {
if(id == null) { document.getElementById("submulti").disabled = true;}
else { document.getElementById("user").value = id;}
});
Well, when there's no cookie the console gives me this:
Error in response to cookies.get: TypeError: Cannot read property 'value' of null
at getCookies [...]
No surprise, but I don't know how to check if the the request worked, and return the error to disable the submit-button.
It would be nice if you could help me..
Thank you,
Markus
Why not just throw in a quick extra check on the value of cookie before attempting to access the value attribute?
chrome.cookies.get({'url': domain, 'name': name}, function(cookie) {
if (callback) {
callback(cookie ? cookie.value : null);
}
});
The ternary check there will make sure you return null when cookie is null. Let me know if that wasn't your question!
Edit2: Yay, found the problem, there is actually an error in the ajax call, and because of my stupidity, I didn't realise that both the methods - success and error can be ran (I thought it was either one or the other), so formComplete was being set to false every time because there was an error.
Appreciate the time you gave & tip about not using global variable names as function parameters.
Edit: Here's the code where formComplete is set (console.log()'s to check formComplete throughout the process):
validate: function(field) {
if(!field.val()) {
formComplete = false;
// formComplete is false here
console.log(formComplete);
}
else {
if(field.attr('name') === 'queryEmail') {
// Validate the email
if(DMOFFAT.helper.validateEmail(field.val()) === true){
// formComplete is either true or false here, depending on the last validation carried out
console.log(formComplete);
formComplete = true;
// formComplete is true here
console.log(formComplete);
}
else {
formComplete = false;
// formComplete is false here
console.log(formComplete);
}
}
else {
formComplete = true;
// formComplete is true here
console.log(formComplete);
}
}
},
Question: Why is this variable (formComplete) going from true to false?
I've written some basic form validation for a contact form, here's how I've done it:
Defined the fields like so:
var queryTypeField = $('#queryType'),
queryMessageField = $('#queryMessage'),
queryEmailField = $('#queryEmail'),
queryNameField = $('#queryName'),
submitButton = $('#submit');
Adding some event handlers to these like so (FWIW, DMOFFAT variable is just an object which holds different modules of the code e.g. contactForm = contact form javascript etc.):
queryMessageField.on('blur', function() {
DMOFFAT.contactForm.validate(queryMessageField);
});
queryNameField.on('blur', function() {
DMOFFAT.contactForm.validate(queryNameField);
});
queryEmailField.on('blur', function() {
DMOFFAT.contactForm.validate(queryEmailField);
});
submitButton.on('click', function(evt) {
evt.preventDefault();
console.log('Click');
console.log(formComplete);
DMOFFAT.contactForm.send(formComplete);
});
The validate function simply sets 'formComplete' to either true or false, depending on if the field is valid or not.
When my fields are all filled in correctly, formComplete = true.
As you can see from the last line of my code above, I pass formComplete (which is true) over to my send function. My send function simply checks the value of formComplete, and either sends the data off to a php script, or prints an error, here's the code:
send: function(formComplete) {
// This is true when the form is filled in correctly
console.log('In send formComplete is...' + formComplete);
if(formComplete === true) {
// Extract form values
formData['queryMessage'] = queryMessage.value;
formData['queryType'] = queryType.value;
formData['queryName'] = queryName.value;
formData['queryEmail'] = queryEmail.value;
$.ajax({
type: 'POST',
async: true,
url: '....',
dataType: 'json',
data: formData,
success: function(data, status, xhr) {
DMOFFAT.contactForm.writeMessage(formComplete);
},
error: function(xhr, status, err) {
DMOFFAT.contactForm.writeMessage(formComplete);
}
});
}
else {
this.writeMessage(formComplete);
}
Now, I KNOW that formComplete is true when the form is filled in correctly, because my php script creates a .txt file with the data in, if it was false, this file wouldn't be created.
This means that we send the value of formComplete off to writeMessage, which simply writes out some HTML to the page to display whether the submission was successful or not, here's the code:
// Disgusting spaghetti code
writeMessage: function(formComplete) {
// This is false now...
console.log('In writeMessage formComplete is...' + formComplete);
if(formComplete === true) {
contactFormElement.html('<div class="success ui-message cf-message"><p><strong>Thank you</strong> for your query, we\'ll get back to you as soon as we can.</p></div>');
}
else {
// Check if there's already an error, otherwise many will appear
if(errorElement === '') {
errorElement = '<div class="error ui-message cf-message"><p>' + this.config.errorMsg + '</p></div>';
contactFormElement.prepend(errorElement);
}
}
}
formComplete itself is defined like so:
var formComplete;
When I inspect formComplete on the first line of writeMessage, it's now false, I cannot find out why though...even when I explicitly set formComplete to true before it's passed to writeMessage, it's still false.
TLDR: Tell me where I'm being stupid please :)
PS: I know I could use a pre-built contact form validation plugin, but wanted to try build something simple myself.
The problem is, that you are calling writeMessage() from a callback function for your AJAX request, so the interpreter is looking for a global variable on execution time. Anyway, you can simply pass true to writeMessage() in your callback functions, as the calls are only executed if formComplete is true-
Basically I have a getjson call to call for a bunch load of data. Now I am getting sick of the amount of if data is null else checks.
For Example:
if (data.Height == "") {
$('#DataHeight').html('No Data is Available');
}
else {
$('#DataHeight').html(data.Height);
}
Reason being is the user has to be alerted asap that data is not available.
So I went off and am trying to write a DataCheck.js to include and handle all this outside of my pretty little page :D.
Function:
function DataNullCheck(ObjectName) {
if (data.ObjectName == "") {
$('"#Data' + ObjectName + '"').html('No Datablurgh');
}
else {
$('"#Data' + ObjectName + '"').html(data.ObjectName);
}
}
and to call it inside my function
function getdata() {
$.ajaxSetup({
cache: false
});
$.getJSON(urldefault, function (data) {
DataNullCheck('Height');
.......
And Data is undefined. Because it is not within the JSON call?
Any help or hints towards the right direction would be appreciated especially an explanation of why it works one way or another. Thanks in advance.
How would I carry through the getJson call functionality to my little function?
Pass data as a parameter to your function:
function DataNullCheck(data, ObjectName) { // you can check for null any property of data
// e.g. DataNullcheck(data, "Width"), or
// DataNullCheck(data, "Height") etc.
if (!data[ObjectName]) {
$('"#Data' + ObjectName + '"').html('No Datablurgh');
}
else {
$('"#Data' + ObjectName + '"').html(data.ObjectName);
}
}