Javascript Logic Fail? - javascript

I'm really confused on this one. I'm trying to do a simple ajax request, and I have php executing 'echo "true";' if the ajax request is successful, or return a string containing the error if it isn't. I'm using this exact technique elsewhere in the code and it compares as expected (msg != "true") { //do something }. The first function I'll post below works with that method, the second doesn't (also I am checking with Firebug the response is "true", and I've done console.log(typeof msg) to verify it is of type string).
This works as expected (the php echoes "true", and it executes show_step2()):
function step2_register() {
var values = $('.signup .txt').serialize();
$.ajax({
type: "POST",
url: base_url+"login/create_account",
data: values,
success: function(msg) {
if (msg != "true") {
$("#login_form.signup .error_container #error1").html(msg).css("visibility", "visible");
}
else {
show_step2();
}
},
error: function(error) {
alert(error);
}
});
}
This doesn't work (the php echoes "true", but the js always executes the slideDown() part of the code):
function register() {
var data = $("#login_form .input").serialize();
$.ajax({
type: "POST",
url: base_url+"login/register",
data: data,
success: function(msg) {
if (msg != "true") {
$("#login_form.signup #error2").html(msg).slideDown();
}
else {
show_success();
}
},
error: function(error) {
alert(error);
}
});
}
What's going on here?

Your php is likely outputting something else invisible like a newline character after the word "true". Either make sure you call die(); or exit(); right after outputting "true", (and doing everything else you need), or make sure there are no line breaks in your PHP editor before the <?php and after the ?>.
You can also check that the string begins with "true" instead of equals "true" by trying something like msg.substring(0,4) == "true"

Related

Updating an input field with PHP vale in JavaScript

I want to update the value of an input field when I receive some information from an api. I tried using:
$('#txtFirstName').val($_SESSION['jUser']['first_name']);
But an error occurs due to the PHP not being able to run in a js file. How can I make this update otherwise? Is there a way in js to update the entire form and input fields without submitting?
I can't reload the entire window, because it will eliminate other information that the user of the website has put in.
1) put value into #txtFirstName from php script
// script.php code
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
echo $_SESSION['jUser']['first_name'];
}
// javascript code
function func(){
$.ajax({
type: "POST",
url: "script.php",
success: function (response) {
$('#txtFirstName').val(response);
},
error: function (e) {
console.log("ERROR : ", e);
}
});
}
2) put value into $_SESSION['jUser']['first_name'] from javascript
// javascript code
function func(){
var your_value = "some_value";
$.ajax({
type: "POST",
url: "script.php",
data: { va: your_value },
success: function (response) {
console.log("value setted to session successfully");
},
error: function (e) {
console.log("ERROR : ", e);
}
});
}
// script.php code
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $_POST['va'] !='') {
$_SESSION['jUser']['first_name'] = $_POST['va'];
echo "ok";
}
Why don't you just echo the value from php script and make an AJAX request from javascript to get the value ? This should be the recommended approach.
However, it can also be accomplished with the approach you've taken:
let first_name = <?php echo $_SESSION['jUser']['first_name']; ?>:
$('#txtFirstName').val(first_name);
For further reading, you can visit How do I embed PHP code in JavaScript?
.

ASP.net/JS/JQuery/AJAX - ajax works but handler event not firing properly

I have a HTTP handler (ASHX) which I am calling from UI side using an AJAX function. The following is what needs to happen in this call:
When the section loads, it will display the status of the short code on the server in the shortcodestatus span. It will either say on or off:
<a class="btn btn-default" id="toggleshortcode">Short Code <span id="shortcodestatus"></span></a>
This is the function for getting the status of the short code and this works properly. I can manually change the status of the short code and the changes reflect properly on the div when I reload the page:
function ShortCodeStatus() {
$.ajax({
type: "GET",
url: "Handler.ashx?action=shortcodestatus",
success: function (output) {
console.log("getShortCodeStatus: " + output);
$("#shortcodestatus").empty();
if (output == "true") {
$("#shortcodestatus").text("ON");
$("#shortcodestatus").addClass("btn btn-success");
}
else {
$("#shortcodestatus").text("OFF");
$("#shortcodestatus").addClass("btn btn-danger");
}
}
});
};
This is the short code status code from the handler:
case "shortcodestatus":
{
output = ShortCodeStatus() ? "true" : "false";
}
break;
I want to be able to click on the toggleshortcode div to fire off this event through the handler. The functions for disabling and enabling the short code are working properly:
case "toggleshortcode":
{
if (ShortCodeStatus() == true)
{
DisableShortCode();
output = "false";
}
else
{
EnableShortCode();
output = "true";
}
}
break;
Here is the ajax call for the short code toggle:
$('#toggleshortcode').click(function () {
$.ajax({
type: "POST",
url: "Handler.ashx?action=toggleshortcode",
success: function (output) {
console.log("toggleshortcode: " + output);
ShortCodeStatus();
}
});
});
I'm hitting the URLs correctly and I'm getting the correct responses from each function. However the change to the short code does not seem to be happening.
For example, if the short code is off, the ShortCodeStatus function will return false and thus render the OFF button. When I click on the toggleshortcode button, the output is true (I want to turn on short code) which is correct but when the ShortCodeStatus function fires again in the success, it will still say false. The ajax functions seem correct but I can't figure out why the toggleshortcode on the handler is not firing properly.
Thank you so much for your time!
I'm seeing 2 cases that you can check.
First, in the ajax call for 'toggleshortcode', you are calling the function 'getShortCodeStatus()', and base on your example the correct name of the function is 'ShortCodeStatus()'.
Second, in the call to 'Handler.ashx?action=toggleshortcode', you are already returning the status (true or false), I suggest you make a javascript function named SetShortCodeStatus(status) , and use this inside of the success of both ajax request 'Handler.ashx?action=shortcodestatus' and 'Handler.ashx?action=toggleshortcode'.
function SetShortCodeStatus(status) {
$("#shortcodestatus").empty();
if (status == "true") {
$("#shortcodestatus").text("ON");
$("#shortcodestatus").addClass("btn btn-success");
}
else {
$("#shortcodestatus").text("OFF");
$("#shortcodestatus").addClass("btn btn-danger");
}
}
function ShortCodeStatus() {
$.ajax({
type: "GET",
url: "Handler.ashx?action=shortcodestatus",
success: function (output) {
console.log("getShortCodeStatus: " + output);
SetShortCodeStatus(output);
}
});
};
$('#toggleshortcode').click(function () {
$.ajax({
type: "POST",
url: "Handler.ashx?action=toggleshortcode",
success: function (output) {
console.log("toggleshortcode: " + output);
SetShortCodeStatus(output);
}
});
});

Check if alert box was shown in PHP using AJAX

I am sending data to a PHP file using AJAX and depending on what data is sent, an alert() is either shown or not shown.
Inside the success function in AJAX, how do I detect if an alert box was shown?
var called = $("#called").val();
$.ajax({
type: "POST",
url: "send.php",
data: "name=" + called,,
success: function(data) {
if(alert box was shown) {
// something happens
}else{
// alert box wasn't shown, something else happens.
}
}
});
send.php:
<?php
if($_POST['name'] == 'john') {
echo'
<script>
alert("Correct name");
</script>
';
}
It would be better to send back a result form the ajax request and show/don't show the alert in the success callback:
$.ajax({
type: "POST",
url: "send.php",
data: "name=" + called,,
success: function(data) {
if ( data == "show" ) {
// something happens
alert("Correct name");
} else {
// alert box wasn't shown, something else happens.
}
}
});
And on your server:
if ( $_POST['name'] == 'john' ) {
echo "show";
}
You could use json_encode() php function to return data from php.
This will be a better approach :
PHP :
if (!isset($_POST['name'] || empty($_POST['name']) {
die(json_encode(array('return' => false, 'error' => "Name was not set or is empty")));
} elseif ($_POST['name'] == "John") {
die(json_encode(array('return' => true)));
} else {
die(json_encode(array('return' => false, 'error' => "Name is different than John.")));
}
At this point, you will be allowed to check the returned values from JS and decide if you need to display the success alert or send an error message to the console (or do what ever you want...).
JS :
var called = $("#called").val();
$.ajax({
type: "POST",
url: "send.php",
dataType: "JSON", // set the type of returned data to json
data: {name: called}, // use more readable syntaxe
success: function(data) {
if (data.return) { // access the json data object
alert("Congrats ! Your name is John !");
} else {
console.log("Sorry, something went wrong : " + data.error);
}
}
});
So, json_encode() allows to return easy accessible object from JS and will also allows you to set and display error messages easily in case the return is false.
Hope it helps !
PHP does not know if an alert has been shown, because in javascript the alert() function has no return value and no events which you could use to send an ajax request a click confirmation to the server.
One solution is to use a confirm() command inside the success event of your $.ajax(), which sends anothe ajax request if the user clicked "ok" or "cancel".
Something like this
var called = $("#called").val();
$.ajax({
type: "POST",
url: "send.php",
data: "name=" + called,
success: function(data) {
if (data == "show") {
var clicked = confirm("Correct name");
if (clicked == true || clicked == false) {
$.ajax({
url: "send.php?clicked=1",
});
}
}
else {
// Whatever to do than...
}
}
});

Request data from server using AJAX and Jquery

I need to create a script that takes data from a form, send it to a server (there's some diabolical C# procedure on it, that's not my job...), the server resolves the string and reply me with 4 strings (yup, they are in spanish): 'pendiente', 'verificada', 'rechazada', and finally 'error'
Now, I have to get that response and properly show the correct message (hidden-inline html).
All this procedure shouldn't "refresh" the actual page, so I'm using AJAX for this.
Have in mind I'm a newbie :) I've learned Jquery just for this task,
and I have to say I'm quite happy with this.
The problem
I don't really know how to handle or "manipulate" that request using Jquery... I figured how to send the data to the server, but I think I'm handling incorrectly the response.
The code:
In this case I've adapted the script, every different response should get its own border color, I'm using conditionals (they are wrong for sure) to add CSS clases to an #ajax div.
So, it might have silly errors...
$(document).ready(function () {
$('#enviar').click(function (event) {
event.preventDefault(); //avoid page refresh
var consulta = $('#string').val();
$("#normal").text(consulta);
//Start AJAX!
$.ajax({
async: true,
cache: false,
type: 'post',
url: 'http://184.22.97.218:8081/chequeostatusdonation', //la del servr
data: {
html: consulta
},
dataType: 'html',
beforeSend: function () {
console.log('Sending...');
},
success: function (data) {
console.log('Just sent -'+data+'- with success dooh');
$('#ajax').html(data);
//start conditional
if (data == pendiente) {
$("#ajax").addClass(pendiente);
} else if (data == verificada) {
$("#ajax").addClass(verificada);
} else if (data == rechazada) {
$("#ajax").addClass(rechazada);
} else {
$("#ajax").html('<h1>error</h1>');
}
//end condicional
},
complete: function () {
console.log('Listo el pollo');
}
});
});
});
Here is the JSFiddle
Edit: Now, I just found these two links
learn.jquery.com/code-organization/concepts/
learn.jquery.com/code-organization/beware-anonymous-functions/
Screw my code! :D
Async is by default "true", so you don't need to mention that one in your code.
You included a link to the server (in the URL-field), but what is the file you are trying to open? You will need to include the path to where you will get the data from (file / script). To make Ajax work, you will need to respect the "same origin policy", so you can insert a relative path to the file / script.
Is the response of your call always a short string with one of those key words ('pendiente', 'verificada', 'rechazada' or 'error)? In that case I would recomment using "text" instead of "html" as dataType, as jQuery will try to parse it to a DOM-structure, which is not what you want here.
Your if-statements (and class-assignments as well) aren't working because you try to compare it to a non-excisting variable instead of the string with that value. You should use " or ' around your string to solve that.
This code should be working. If not, let me know. Include the error given in the console of the browser.
$(document).ready(function () {
$('#enviar').click(function (event) {
event.preventDefault(); //avoid page refresh
var consulta = $('#string').val();
$("#normal").text(consulta);
//Start AJAX!
$.ajax({
type: 'POST',
cache: false,
url: 'RELATIVE_PATH_HERE', //la del servr
data: {
html: consulta
},
dataType: 'text',
beforeSend: function () {
console.log('Sending...');
},
success: function (data) {
console.log('Just sent -'+data+'- with success dooh');
$('#ajax').html(data);
//start conditional
if (data === 'pendiente') {
$("#ajax").addClass('pendiente');
} else if (data === 'verificada') {
$("#ajax").addClass('verificada');
} else if (data === 'rechazada') {
$("#ajax").addClass('rechazada');
} else {
$("#ajax").html('<h1>error</h1>');
}
//end condicional
},
complete: function () {
console.log('Listo el pollo');
},
error: function() {
console.log('Problem with XHR-request');
});
});
});
Be careful with .addClass if you process multiple Ajax-calls as they will add on each other.

PHP/ Ajax/ jQuery - Equivalent for my code

I have the following code and would like to use jquery to make it simpler:
var auctionBidAjax;
function auctionBid(auction_id) {
auctionBidAjax=GetXmlHttpObject();
if (auctionBidAjax==null) {
alert ("Your browser does not support XMLHTTP!");
return;
}
var url="/cms/ajax/auctionBid.php?auction_id="+auction_id;
auctionBidAjax.onreadystatechange=function() { auctionBidReady(auction_id); };
auctionBidAjax.open("GET",url,true);
auctionBidAjax.send(null);
}
And...
function auctionBidReady(auction_id) {
if (auctionBidAjax.readyState==4) {
if (auctionBidAjax.responseText == "Bid Placed") {
document.getElementById('auctionBid' + auction_id).innerHTML=
"Place Bid";
userBids();
} else if (auctionBidAjax.responseText == "Not Logged In") {
popupCentre('popupLogin');
popupLoad('popupLogin');
} else if (auctionBidAjax.responseText == "No Bids"){
popupCentre('popupNoBids');
popupLoad('popupNoBids');
}
}
}
My PHP script adds a bid etc and echos the responseText.
You've tagged this question as jquery so you can use $.ajax():
function auctionBid(auction_id) {
$.ajax({
url: "/cms/ajax/auctionBid.php",
type: "GET",
data: {
auction_id: auction_id
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
// act appropriately
},
success: function(data, textStatus) {
// do whatever
}
});
}
If you didn't need an error handler you could use the simpler form of $.get() instead:
function auctionBid(auction_id) {
var url = "/cms/ajax/auctionBid.php";
$.get(url, { auction_id: auction_id }, function(data, textStatus) {
// do whatever
});
}
I actually prefer not to use error handlers. It's a little uglier than it needs to be. Use that for actual errors. Things like "not logged in" could be handled by the success handler. Just pass back a JSON object that contains the required information to tell the user what happened.
For this you could use the $.getJSON() shorthand version.
function auctionBid(auction_id) {
var url = "/cms/ajax/auctionBid.php";
$.getJSON(url, { auction_id: auction_id }, function(data) {
if (data.notLoggedIn) {
alert("Not logged in");
}
...
});
}
To return some information as JSON from PHP use json_encode() and set the MIME type appropriately:
<?php
session_start();
header('Content-Type: application/json');
echo json_encode(array(
'highBid' => get_new_high_bid(),
'loggedIn' => $_SESSION['loggedIn'],
));
exit;
?>
I'm making assumptions about your login system so the above is a gross simplification.
Return that to a $.getJSON() callback and you should be able to do:
alert(data.highBid);
alert(data.loggedIn);
JQuery.get is what you need
http://docs.jquery.com/Ajax/jQuery.get

Categories

Resources