Get multiple data from an Ajax response - php

When process.php responds to an Ajax request made by form.html it replies with "false" or "true [hash value]" (where hash value is the output of a hashing function). In form.html I want to call a different function for the two possible responses but how do I parse the response? For example must I call
var responses = xmlhttp.responseText.split(" ")
Assuming the hashing function never outputs "false" I could use
if(xmlhttp.responseText != "false")
Both these ways seem kind of hacky and inefficent, is there a better way?

You could do the following in your PHP Code:
$returnValue['ValueA'] = "a value";
$returnValue['ValueB'] = "another value";
echo json_encode($returnValue);
in your JavaScript Code (JQuery is used here):
$.ajax({
type: "GET",
dataType: "json",
url: "./myphpfile.php",
data: "parameter=parametervalue",
success: function(data){
printresult(data);
}
});
function printresult(data)
{
alert(data['ValueA']);
alert(data['ValueB']);
}
Is this helping you?

I've had a similar situation, here is my solution using basic Javascript.
First on the PHP side, I can have one of four outcomes (PASS or FAIL on an INSert or UPDate), so my response to AJAX carries those outcomes upfront:
[...]
$echoStr = 'PASS/INS/Adding ID Succeeded.'; // INSert successful
[...]
$echoStr = 'FAIL/INS/Adding ID Failed'; // INSert failed
[...]
$echoStr = 'PASS/UPD/Updating D Succeeded.'; // UPDate successful
[...]
$echoStr = 'FAIL/UPD/Updating ID Failed'; // UPDate failed
[...]
echo $echoStr; return; // Reply to AJAX request.
On the Javascript side (ajax1 is my AJAX obj), I split the response string into three components and process accordingly:
[...]
ajax1.onreadystatechange = function() {
if (ajax1.readyState == 4 && ajax1.status == 200) {
response = ajax1.responseText; // PASS or FAIL, INS or UPD, free form text alert
passFail = response.substr(0,4); // PASS or FAIL
insUPD = response.substr(5,3); // INS or UPD
usrMsg = response.substr(9); // Free form alert text
if (passFail == 'PASS' && insUPD == 'INS') {
// do what you need to do here
}
alert(usrMsg);
} // if (ajax1.readyState == 4 && ajax1.status == 200) {
} // ajax1.onreadystatechange = function() {
[...]

Related

How to focus on a form field only if my data variable is not empty

I have been using php and ajax to validate if an email inserted in my form exists in my database.
I am using jquery to send the email value to my php file and return a message if the email is found. My code is working fine but I want if an email is found the cursor be on focus on the #usu_email field until the email be changed. After this, it should allow me to continue to next field.
This is the jquery code I am using:
function getemail(value) {
var usumail = $("#usu_email").val();
$.ajax({
type: "POST",
url: "ajax_email.php",
data: "usu_email=" + usumail,
success: function(data, textStatus) {
if (data !== null) {
$("#eresult").html(data);
$("#usu_email").focus();
}
},
});
};
My problem is that if and email does not exist in my database the cursor keeps doing focus on my #usu_email field and does not allow me to continue to next field.
I will appreciate any help about this problem because I know very little about jquery.
First... Your condition if (data !== null) always will be true since there always will be a data provided... Be it an empty string.
The only case where there will be no data is on Ajax error... And the condition won't even be evaluated because the success callback won't execute.
Next, I assume that your Ajax request is triggered on $("#usu_email") blur... Else, I don't know how you achieve «does not allow me to continue».
Modify it in this way to compare a response:
function getemail(value) {
var usumail = $("#usu_email").val();
$.ajax({
type: "POST",
url: "ajax_email.php",
data: "usu_email=" + usumail,
datatype: "json",
success: function(data) { // There is only one argument here.
// Display the result message
$("#eresult").html(data.message);
if (data.email_exist == "yes") {
$("#usu_email").focus();
}
if (data.email_exist == "no") {
// Something else to do in this case, like focussing the next field.
}
},
});
};
On the PHP side, you have to provide the json response. It would look like something like this:
<?php
// You have this variable to compare against the database
$email = $_POST[usu_email];
// You say it is working.
// ...
// Then, you certainly have a result... Say it's $found (true/false).
// Build an array of all the response param you want to send as a response.
if($found){
$result[email_exist] = "yes";
$result[message] = "The submitted email already exist.";
}else{
$result[email_exist] = "no";
$result[message] = "A success message about the email here.";
}
// Add this header to the returned document to make it a valid json that doesn't need to be parsed by the client-side.
header("Content-type:application/json");
// Encode the array as a json and print it. That's what is sent in data as an Ajax response.
echo json_encode($result);
?>
Be carefull not to echo anything else. Not even a blank space or a line return.
Depends on what type of data you're expecting (simple text response or JSON), but at first i would start to replace your if(data !== null) with if(typeof data != "undefined" && data !== null && data != "") because the returned response might just be empty and not NULL.
If it doesn't work you should consider adding your php code to the question so we can figure out exactly what it returns when no matching email is found.

Ajax function learning

I need help in Ajax.
I got this code online.
This function is to check the contact.php
I have some few question so someone could assist me.
My questions :
1. Is this code good and possible to run ?
2. Can someone explain me what does the function in line 4 and line 5 does.It seems it send data to the contact.php but what is it returning?
Ajax:
var validateEmailForm = {
dataType: 'json',
submit: function(form) {
var redirect = false;
$.ajax('contact.php', {data:{'email':form.email.value}}).done(function(data) {
if ( typeof(data) == 'object' ) {
if ( data.status == 'valid') {
form.submit();
} else if(data.status !=='valid' {
alert('The e-mail address entered is wrong.');
}
} else {
alert('Failed to connect to the server.');
}
}
}
}
Contact.php:
<?php
error_reporting(0);
$email = $_POST['email'];
if (isset($_$POST['email']))
{
// How to return valid to the ajax
} else {
// How to return invalid to the ajax.
}
?>
You need to return a JSON_encoded array to the ajax function, like below:
$email = $_POST['email'];
$status = false;
if (isset($_$POST['email']))
{
$status = 'success'
} else {
$status = false
}
echo json_encode(array('status' => $status));
?>
Further, add dataType: 'json' to your $.ajax() so that the deferred function automatically parses it as such.
Remove the typeof() as we know what we're expecting in return.
AJAX is much easier than it sounds. You just need to see a few good examples.
Try these:
A simple example
More complicated example
Populate dropdown 2 based on selection in dropdown 1
https://stackoverflow.com/questions/25945137/php-fetch-content-from-one-form-and-update-it-in-other-form/25954450#25954450
The above examples demonstrate a few things:
(1) There are four formats for an AJAX request - the full $.ajax() structure, and three shortcut structures ($.post(), $.get(), and $.load() )
Until you are pretty good at AJAX, I suggest using a correctly formatted $.ajax() code block, which is what the above examples demonstrate. Such a code block looks like this:
$('#formID').submit({
$.ajax({
type: 'post',
url: 'contact.php',
dataType: 'json',
data: 'email=' + form.email.value
}).done(function(data) {
if ( typeof(data) == 'object' ) {
if ( data.status == 'valid') {
form.submit();
} else if(data.status !=='valid' {
alert('The e-mail address entered is wrong.');
return false;
} else {
alert('Failed to connect to the server.');
return false;
}
}
});
});
(2) In an $.ajax() code block, the data: line specifies the data that is sent to the PHP processor file.
(3) The dataType: line specifies the type of data that the ajax code block expects to receive back from the PHP processor file. The default dataType is html, unless otherwise specified.
(4) In the PHP processor file, data is returned to the AJAX code block via the echo command. Whether that data is returned as html, text, or json, it is echoed back to the AJAX routine, like this:
<?php
//perform MySQL search here. For eg, get array $result with: $result['firstname'] and $result['lastname']
$out = '<div id="myresponse">';
$out .= 'First Name: <input type="text" value="' .$result['firstname']. '" />';
$out .= 'Last Name: <input type="text" value="' .$result['lastname']. '" />';
$out .= '</div>';
echo $out;
Please try a couple of the above examples for yourself and you will see how it works.
It is not necessary to use json to send/return data. However, json is a useful format to send array data, but as you can see, you can construct a full html response on the PHP side and echo back the finished markup.
So, to definitively answer your second question, you just need to echo back some data. It is the job of the PHP file to:
(1) receive the data from the AJAX routine,
(2) Use that data in a look up of some kind (usually in a database),
(3) Construct a response, and
(4) echo (NOT return) the response back to the AJAX routine's success: or .done() functions.

Calling a specific function from PHP with Jquery & Ajax

For me this is something new, so I am just researching this and trying to understand it.
As you can see in the php script there are 2 functions and I am trying to call a specific one with jquery.
Now if I have one function then I can do it, but when I have 2 or more I am starting to get stuck.
I suppose I could do this when I have 2 functions, but as soon as more variables are in play or more functions do I just make massive if statements in my php?
The problem is that when I attach a database to it, I would need to consider all inputs that can happen.
How do I specify a specific php function when using jquery & ajax?
//function.php
<?php
function firstFunction($name)
{
echo "Hello - this is the first function";
}
function secondFunction($name)
{
echo "Now I am calling the second function";
}
?>
<?php
$var = $_POST['name'];
if(isset($var))
{
$getData = firstFunction($var);
}
else if(isset($var))
{
$getData = secondFunction($var);
}
else
{
echo "No Result";
}
?>
//index.html
<div id="calling">This text is going to change></div>
<script>
$(document).ready(function() {
$('#calling').load(function() {
$.ajax({
cache: false,
type: "POST",
url: "function.php",
data: 'name=myname'
success: function(msg)
{
$('#calling').html((msg));
}
}); // Ajax Call
}); //event handler
}); //document.ready
</script>
You need to pass a parameter in, either via the data object or via a GET variable on the URL. Either:
url: "function.php?action=functionname"
or:
data: {
name: 'myname',
action: 'functionname'
}
Then in PHP, you can access that attribute and handle it:
if(isset($_POST['action']) && function_exists($_POST['action'])) {
$action = $_POST['action'];
$var = isset($_POST['name']) ? $_POST['name'] : null;
$getData = $action($var);
// do whatever with the result
}
Note: a better idea for security reasons would be to whitelist the available functions that can be called, e.g.:
switch($action) {
case 'functionOne':
case 'functionTwo':
case 'thirdOKFunction':
break;
default:
die('Access denied for this function!');
}
Implementation example:
// PHP:
function foo($arg1) {
return $arg1 . '123';
}
// ...
echo $action($var);
// jQuery:
data: {
name: 'bar',
action: 'foo'
},
success: function(res) {
console.log(res); // bar123
}
You are actually quite close to what you want to achieve.
If you want to specify which function will be called in PHP, you can pass a variable to tell PHP. For example, you passed request=save in AJAX, you can write the PHP as follow:
$request = '';
switch(trim($_POST['request'])) {
case 'save':
$player_name = (isset($_POST['playername']) ? trim($_POST['player_name']) : 'No Name'));
saveFunction($player_name);
break;
case 'load':
loadFunction();
break;
default:
// unknown / missing request
}
EDIT: You can even pass along with other parameters
This may not be exactly what you are looking for but it can help some others looking for a very simple solution.
In your jquery declare a variable and send it
var count_id = "count";
data:
{
count_id: count_id
},
Then in your php check if this variable is set
if(isset($_POST['count_id'])) {
Your function here
}

Ajax success if statement and echo mySQL query result

I have an Ajax script that makes a call to a php file on my server every twenty seconds.
The server then runs a simple mysql query to return the contents of a particular field.
If that field is blank I want the php file to echo the word "pending", which when caught by the success handler will recall the initial function. However if that field is not blank, it will contain a URL to which I want to redirect the user to. That field will update any where between 5 seconds and 5 minutes from the start of the first call and that time cannot be changed.
I think the main issue may be with my php file, in that I dont think it is echoing the data in a way that the success handler recognises. However I have detailed both parts of my code as whilst the success handler seems to be constructed correctly I am not 100% sure.
Very new to this, so apologies if I have not explained myself correctly but if anyone could assist that would be great:
UPDATE - for clarity what I am looking to achieve is as follows:
Ajax call to my php file.
PHP file queries database
If field queried contains no data echo the word "pending" to the ajax success handler (IF) which in turn recalls the original function / ajax call.
If field queried contains data (will be a URL) echo this result to the ajax success handler (ELSE)in a format that will redirect the user via window.location.assign(data).
FURTHER UPDATE
I managed to solve this question with using a combination of the advice from #mamdouhalramadan and #martijn
I also have changed setInterval to setTimeout as the poll function was causing responses to stack up should the server be running slowly and as such cause errors. I also added in cache: false and a further option in the success handler to take into account slightly different behaviour in IE:
AJAX
function poll() {
$.ajax({
url: 'processthree.php?lead_id='+lead_id,
type: "GET",
cache: false,
async: false,
success: function(data3) {
//alert("pending called " + data3)
if(data3.indexOf("pending") >-1 ){
setTimeout(poll, 20000);
}
else if ( (navigator.userAgent.indexOf('MSIE') != -1) ) {
//alert("Submit success - MSIE: " + data3);
parent.window.location.replace(data3);
}
else{
//alert("process three called " + data3)
window.top.location.assign(data3);
}
},
error: function(xhr, error){
//alert("Error");
//alert("Error: " + error + ", XHR status: " + xhr.status);
},
});
}
setTimeout(poll, 20000);
PHP
$query = ("SELECT column FROM table WHERE id = '$lead_id'") or die(mysql_error());
$result = mysql_query($query);
$return = array();
while($row = mysql_fetch_assoc($result))
{
$return = 'pending';
if($row['column'] != '')
{
$return = $row['column'];
}
}
echo $return;
I believe using json might help you out here, not to mention it is safer, like so:
function poll() {
$.ajax({
url: 'processthree.php?lead_id='+lead_id,
type: "GET",
dataType: 'json',//specify data type
success: function(data3) {
if(data3.res.indexOf("pending") >-1 ){
//rest of the code.....
then in your php:
$return = array();
while($row = mysql_fetch_assoc($result))
{
$return['res'] = 'pending';
if($row['column'] != '')
{
$return['res'] = $row['column'];
}
}
echo json_encode($return);
Note: use PDO or MYSQLI instead of mysql as it is deprecated.

How to validate password with jquery and php?

I've never done this before, and I haven't found much help on Google or StackOverflow yet.
Here's what I have: A password input:
<input type="text" placeholder="password" name="pass" id="password" />
and some jQuery to check the password:
<script>
$('form').submit(function(){
input = $('#password').val();
var finish = $.post("pass.php", { request: "opensesame" }, function(data) {
return (input==data) ? true : false;
});
if(finish){
alert('sent');
}else{
alert('not sent');
}
return false;
});
</script>
And a password-dispensing php page (pass.php):
<?php
if(isset($_POST['request'])&&$_POST['request']=="opensesame"){
echo 'graphics';
}
?>
Now, I can get it to alert 'graphics', but I can't get it to match the data with the input value to check if it's the right password or not.
What am I doing wrong, and what are the potential dangers to authenticating a password in this way?
The "A" in "AJAX" stands for asynchronous.
The code after you call $post will execute before the contents of the $post function. The value of finish will always be a jqXHR object, the result of (input==data) ? true : false will be ignored.
More clearly:
var finish = $.post("pass.php", { request: "opensesame" }, function(data) {
// THIS EXECUTES SECOND, and the return value is discarded
return (input==data) ? true : false;
});
// THIS EXECUTES FIRST, with finish set to a jqXHR object
if(finish){
...
You need to rethink your methods of password checking, or use synchronous postbacks by adding the following before your $.post calls:
$.ajaxSetup({async:false});
Or by using $.ajax and passing async: false:
jQuery.ajax({
type: 'POST',
url: "pass.php",
data: { request: "opensesame" },
success: function(result) { ... },
async: false
});
The first thing to do would be to clean up the code, it's too obscure, I'm afraid.
I'd write it as follows:
<script>
$('form').submit(function(event){
event.preventDefault(); // stop the form from submitting
var passwd = $('#password').val();
var finish = $.post("pass.php", { request: passwd }, function(data) {
if(data){
alert('Success!');
}else{
alert('Failure :(');
}
});
});
</script>
Things to note here:
AJAX POST is asynchronous, you can't check for a variable right after changing it in the callback, you need to process stuff inside the callback.
You must verify the password on the server, not in javascript!!
Adding to the previous bullet, don't write your password inside the javascript!
And on the server:
<?php
if(isset($_POST['request']) && $_POST['request']=="opensesame"){
echo 'true';
}else{
echo 'false';
}
?>
Things to note here:
You used isset() to check for the existence of the variable, good call. Keep doing it.
jQuery POST expects a javascript value from the server (unless you tell it otherwise).
This is why my code prints either 'true' or 'false', this translates to a boolean value in javascript.
I would advise returning an object with error details, such as the one below:
<?php
$result = array('success'=>false, 'reason'=>'Unknown error.');
if(isset($_POST['request'])){
if(trim($_POST['request'])!=''){
if($_POST['request']=='opensesame'){
$result['success'] = true;
$result['reason'] = 'Welcome home!';
}else $result['reason'] = 'Password is wrong';
}else $result['reason'] = 'Password must not be empty';
}else $result['reason'] = 'Expected parameter "request"';
echo json_encode($result);
?>
You have to serialize your input fields to all the data to your script:
$.post("pass.php", { request: $('form').serialize() }, function(data) {
// ...
As long as you are on your own server I don't see much potential dangers, as it sends a POST-request which a normal form would do anyway.
Its quite unsafe to send data like this, anyone can intercept and read the data which you send by ajax and the value returned by ajax using firebug or other such tools. So you should serialize or sanitize the fields and also encrypt the data before sending them.
& the code to alert after checking finish will be executed before the response comes from ajax (note that it is asynchronous) thus you would get an object stored in the finish variable.

Categories