Ajax function learning - php

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.

Related

Passing of javascript variable data to php variable in the same php file

I have a javascript that needs to pass data to a php variable. I already searched on how to implement this but I cant make it work properly. Here is what I've done:
Javascript:
$(document).ready(function() {
$(".filter").click(function() {
var val = $(this).attr('data-rel');
//check value
alert($(this).attr('data-rel'));
$.ajax({
type: "POST",
url: 'signage.php',
data: "subDir=" + val,
success: function(data)
{
alert("success!");
}
});
});
});
Then on my php tag:
<?php
if(isset($_GET['subDir']))
{
$subDir = $_GET['subDir'];
echo($subDir);
}
else
{
echo('fail');
}?>
I always get the fail text so there must be something wrong. I just started on php and jquery, I dont know what is wrong. Please I need your help. By the way, they are on the same file which is signage.php .Thanks in advance!
When you answer to a POST call that way, you need three things - read the data from _POST, put it there properly, and answer in JSON.
$.ajax({
type: "POST",
url: 'signage.php',
data: {
subDir: val,
}
success: function(answer)
{
alert("server said: " + answer.data);
}
});
or also:
$.post(
'signage.php',
{
subDir: val
},
function(answer){
alert("server said: " + answer.data);
}
}
Then in the response:
<?php
if (array_key_exists('subDir', $_POST)) {
$subDir = $_POST['subDir'];
$answer = array(
'data' => "You said, '{$subDir}'",
);
header("Content-Type: application/json;charset=utf-8");
print json_encode($answer);
exit();
}
Note that in the response, you have to set the Content-Type and you must send valid JSON, which normally means you have to exit immediately after sending the JSON packet in order to be sure not to send anything else. Also, the response must come as soon as possible and must not contain anything else before (not even some invisible BOM character before the
Note also that using isset is risky, because you cannot send some values that are equivalent to unset (for example the boolean false, or an empty string). If you want to check that _POST actually contains a subDir key, then use explicitly array_key_exists (for the same reason in Javascript you will sometimes use hasOwnProperty).
Finally, since you use a single file, you must consider that when opening the file the first time, _POST will be empty, so you will start with "fail" displayed! You had already begun remediating this by using _POST:
_POST means that this is an AJAX call
_GET means that this is the normal opening of signage.php
So you would do something like:
<?php // NO HTML BEFORE THIS POINT. NO OUTPUT AT ALL, ACTUALLY,
// OR $.post() WILL FAIL.
if (!empty($_POST)) {
// AJAX call. Do whatever you want, but the script must not
// get out of this if() alive.
exit(); // Ensure it doesn't.
}
// Normal _GET opening of the page (i.e. we display HTML here).
A surer way to check is verifying the XHR status of the request with an ancillary function such as:
/**
* isXHR. Answers the question, "Was I called through AJAX?".
* #return boolean
*/
function isXHR() {
$key = 'HTTP_X_REQUESTED_WITH';
return array_key_exists($key, $_SERVER)
&& ('xmlhttprequest'
== strtolower($_SERVER[$key])
)
;
}
Now you would have:
if (isXHR()) {
// Now you can use both $.post() or $.get()
exit();
}
and actually you could offload your AJAX code into another file:
if (isXHR()) {
include('signage-ajax.php');
exit();
}
You are send data using POST method and getting is using GET
<?php
if(isset($_POST['subDir']))
{
$subDir = $_POST['subDir'];
echo($subDir);
}
else
{
echo('fail');
}?>
You have used method POST in ajax so you must change to POST in php as well.
<?php
if(isset($_POST['subDir']))
{
$subDir = $_POST['subDir'];
echo($subDir);
}
else
{
echo('fail');
}?>
Edit your javascript code change POST to GET in ajax type
$(document).ready(function() {
$(".filter").click(function() {
var val = $(this).attr('data-rel');
//check value
alert($(this).attr('data-rel'));
$.ajax({
type: "GET",
url: 'signage.php',
data: "subDir=" + val,
success: function(data)
{
alert("success!");
}
});
});
});
when you use $_GET you have to set you data value in your url, I mean
$.ajax({
type: "POST",
url: 'signage.php?subDir=' + val,
data: "subDir=" + val,
success: function(data)
{
alert("success!");
}
});
or change your server side code from $_GET to $_POST

Why the static message is not coming from ajax file if no data found in mysql database?

I have a very strange problem and couldn't figure it out. I am working with AJAX/PHP and fetching the data from mysql database on user interaction by ajax call. Everything is working very fine and no problem at all. But only one issue which is persisting is when the data is not found in mysql database, then a user-friendly message is not returned from the server ajax file - the one part works and other doesn't. Here is my code -
This is my first file where the form reside (full code is not there; only js code) -
<script type="text/javascript">
$(document).ready(function(){
$("#selcustomer").change(function(){
var customers_id = $(this).val();
if(customers_id > 0)
{
$.ajax({
beforeSend: startRequest,
url: "ajax/ajax.php",
cache: false,
data: "customers_id="+customers_id,
type: "POST",
dataType: "json",
success: function(data){
if(data != "No result found.")
{
$("#img_preloader").hide();
$("#error").html('');
// $("#txtfname").val(data.fname);
// $("#txtlname").val(data.lname);
for(var key in data)
{
document.getElementById("txt"+key).value = data[key];
}
}
else
{
$("#img_preloader").hide();
$("#error").html(data);
$("input").each(function(){
$(this).val('');
});
}
}
});
}
else
{
$("#error").html('');
$("input").each(function(){
$(this).val('');
});
}
});
});
function startRequest()
{
$("#img_preloader").show();
}
</script>
And this is my server-side ajax file (php file) which interacts with database -
<?php
include("../includes/db-config.php");
if(isset($_POST["customers_id"]))
{
$customers_id = $_POST["customers_id"];
$query = "SELECT * FROM `tb_customers` WHERE `customers_id` = '$customers_id'";
$rs = mysql_query($query);
if(mysql_num_rows($rs) > 0)
{
$row = mysql_fetch_array($rs);
$customers_first_name = $row['customers_first_name'];
$customers_last_name = $row['customers_last_name'];
$customers_email_id = $row['customers_email_id'];
$customers_phone_no = $row['customers_phone_no'];
$customers_address_line_1 = $row['customers_address_line_1'];
$customers_address_line_2 = $row['customers_address_line_2'];
$customers_country = $row['customers_country'];
$data = array('fname' => $customers_first_name, 'lname' => $customers_last_name, 'emailid' => $customers_email_id, 'phoneno' => $customers_phone_no, 'addressline1' => $customers_address_line_1, 'addressline2' => $customers_address_line_2, 'country' => $customers_country);
echo json_encode($data);
}
else
{
echo "No result found.";
}
}
?>
The if part is working fine but when no data is found in database the else part is not sending the data back to jQuery code. I checked in browser console and saw the else part is returning the response but the jquery code in success: part of $.ajax is not running - neither within if, nor in else and also not outside of if/else. I mean to say that a simple alert is not fired with data under success when no data is found in mysql database. But when i remove all the data in ajax/php file and say simply write 123 then alert comes with 123 but not when the actual code is there. Can you plz tell me what is the issue behind this strange problem?
Your datatype is set to JSON in your AJAX call, so the return value must be a valid JSON.
When you are encountering the else condition, you are returning something that is not JSON.
Try this -
else
{
echo json_encode("No result found.");
}
Or something more flexible-
else{
echo json_encode(Array("err"=>"No result found."));
}
EDIT-
...But when i remove all the data in ajax/php file and say simply write
123 then alert comes with 123...
That is because a 123 (number) is valid JSON. Instead of 123, try writing No result and an error would be thrown, because No result (a string) needs quotes(which is taken care when you use json_encode).

Ajax returning object instead of data

What is the correct way to handle Ajax success callback events using jquery?
In my code, when I run instead of displaying data, it alerts object:object. However, if I use say msg.box it returns the data correctly.
I am trying to create an if statement where if text equals a certain word then the variable from json is placed in the html of the result div BA_addbox.
I cannot seem to get this to work and would be grateful if someone could point out my error. I have only included the relevant code as the form is posting the correct data and the php code is catching all the posts. Many thanks.
ajax code
$.ajax({
type: "POST",
url: "/domain/admin/requests/boxes/boxesadd.php",
data: formdata,
dataType: 'json',
success: function(msg){
if(msg == "You need to input a box") {
$("#BA_addbox").html(msg.boxerrortext);
}
else {
$("#BA_addbox").html(msg.box);
}
//alert(msg);
console.log(msg);
//$("#BA_addbox").html(msg.box);
//$("#formImage .col_1 li").show();
//$("#BA_boxform").get(0).reset();
//$("#boxaddform").hide();
}
});
boxesadd.php
$box = mysql_real_escape_string($_POST['BA_box']);
$boxerrortext = "You need to input a box";
if (isset($_POST['submit'])) {
if (!empty($box)) {
$form = array('dept'=>$dept, 'company'=>$company, 'address'=>$address, 'service'=>$service, 'box'=>$box, 'destroydate'=>$destroydate, 'authorised'=>$authorised, 'submit'=>$submit);
$result = json_encode($form);
echo $result;
}
else
{
$error = array('boxerrortext'=>$boxerrortext);
$output = json_encode($error);
echo $output;
//echo "You need to input a box";
}
}
In javascript associative arrays are called objects, so there's no bug in the transmitted data.
Why do you compare msg to "You need to input a box"? You cannot compare object and string, this makes no sense.
if(typeof msg.boxerrortext !== "undefined" && msg.boxerrortext == "You need to input a box") {
$("#BA_addbox").html(msg.boxerrortext);
} else {
$("#BA_addbox").html(msg.box);
}
Try this instead:
if(msg.boxerrortext) {
$("#BA_addbox").html(msg.boxerrortext);
}
else {
$("#BA_addbox").html(msg.box);
}
Hope this will help !!

Sending data with AJAX to a PHP file and using that data to run a PHP script

I'm currently trying to make live form validation with PHP and AJAX. So basically - I need to send the value of a field through AJAX to a PHP script(I can do that) and then I need to run a function inside that PHP file with the data I sent. How can I do that?
JQuery:
$.ajax({
type: 'POST',
url: 'validate.php',
data: 'user=' + t.value, //(t.value = this.value),
cache: false,
success: function(data) {
someId.html(data);
}
});
Validate.php:
// Now I need to use the "user" value I sent in this function, how can I do this?
function check_user($user) {
//process the data
}
If I don't use functions and just raw php in validate.php the data gets sent and the code inside it executed and everything works as I like, but if I add every feature I want things get very messy so I prefer using separate functions.
I removed a lot of code that was not relevant to make it short.
1) This doesn't look nice
data: 'user=' + t.value, //(t.value = this.value),
This is nice
data: {user: t.value},
2) Use $_POST
function check_user($user) {
//process the data
}
check_user($_POST['user'])
You just have to call the function inside your file.
if(isset($_REQUEST['user'])){
check_user($_REQUEST['user']);
}
In your validate.php you will receive classic POST request. You can easily call the function depending on which variable you are testing, like this:
<?php
if (isset($_POST['user'])) {
$result = check_user($_POST['user']);
}
elseif (isset($_POST['email'])) {
$result = check_email($_POST['email']);
}
elseif (...) {
// ...
}
// returning validation result as JSON
echo json_encode(array("result" => $result));
exit();
function check_user($user) {
//process the data
return true; // or flase
}
function check_email($email) {
//process the data
return true; // or false
}
// ...
?>
The data is send in the $_POST global variable. You can access it when calling the check_user function:
check_user($_POST['user']);
If you do this however remember to check the field value, whether no mallicious content has been sent inside it.
Here's how I do it
Jquery Request
$.ajax({
type: 'POST',
url: "ajax/transferstation-lookup.php",
data: {
'supplier': $("select#usedsupplier").val(),
'csl': $("#csl").val()
},
success: function(data){
if (data["queryresult"]==true) {
//add returned html to page
$("#destinationtd").html(data["returnedhtml"]);
} else {
jAlert('No waste destinations found for this supplier please select a different supplier', 'NO WASTE DESTINATIONS FOR SUPPLIER', function(result){ return false; });
}
},
dataType: 'json'
});
PHP Page
Just takes the 2 input
$supplier = mysqli_real_escape_string($db->mysqli,$_POST["supplier"]);
$clientservicelevel = mysqli_real_escape_string($db->mysqli,$_POST["csl"]);
Runs them through a query. Now in my case I just return raw html stored inside a json array with a check flag saying query has been successful or failed like this
$messages = array("queryresult"=>true,"returnedhtml"=>$html);
echo json_encode($messages); //encode and send message back to javascript
If you look back at my initial javascript you'll see I have conditionals on queryresult and then just spit out the raw html back into a div you can do whatever you need with it though.

How can I "read" a response from the php file I call here using ajax?

I am very new to ajax and jquery, but I came across a code on the web which I am manipulating to suit my needs.
The only problem is that I want to be able to respond to the ajax from PHP.
This ajax POSTS to a php page (email.php).
How can I make the email.php reply back if the message is sent or if message-limit is exceeded (I limit the nr of messages sent per each user)?
In other words, I want ajax to take a 1 or 0 from the php code, and for example:
if(response==1){ alert("message sent"); } else { alert("Limit exceeded"); }
Here is the last part of the code: (If you need the full code just let me know)
var data_string = $('form#ajax_form').serialize();
$.ajax({
type: "POST",
url: "email.php",
data: data_string,
success: function() {
$('form#ajax_form').slideUp('slow').before('');
$('#success').html('<h3>Success</h3>Your email is has been sent.');
}//end success function
}) //end ajax call
return false;
})
Thanks
The success function of an $.ajax call receives a parameter, usually called data though that's up to you, containing the response, so:
success: function(data) {
// Use the data
}
(It also receives a couple of other parameters if you want them; more in the docs.)
The data parameter's type will vary depending on the content type of the response your PHP page sends. If it sends HTML, data will be a string containing the HTML markup; if your page sends JSON, the data parameter will be the decoded JSON object; if it's XML, data will be an XML document instance.
You can use 1 or 0 if you like (if you do, I'd probably set the content type to "text/plain"), so:
success: function(data) {
if (data === "1") {
// success
}
else if (data === "0") {
// failure
}
else {
// App error, expected "0" or "1"
}
}
...but when I'm responding to Ajax requests, nine times out of ten I send JSON back (so I set the Content-Type header to application/json), because then if I'm using a library like jQuery that understands JSON, I'll get back a nice orderly object that's easy to work with. I'm not a PHP guy, but I believe you'd set the content type via setContentType and use json_encode to encode the data to send back.
In your case, I'd probably reply with:
{"success": "true"}
or
{"success": "false", "errMessage": "You reached the limit."}
so that the server-side code can dictate what error message I show the user. Then your success function would look like this:
success: function(data) {
var msg;
if (typeof data !== "object") {
// Strange, we should have gotten back an object
msg = "Application error";
}
else if (!data.success) {
// `success` is false or missing, grab the error message
// or a fallback if it's missing
msg = data.errMessage || "Request failed, no error given";
}
if (msg) {
// Show the message -- you can use `alert` or whatever
}
}
You must pass an argument to your "success" function.
success: function(data)
{
if(data == '1')
{
$('form#ajax_form').slideUp('slow').before('');
$('#success').html('<h3>Success</h3>Your email is has been sent.');
}
}
And in your php file, you should just echo the response you need
if(mail())
{
echo '1';
}
else
{
echo '0';
}
Anything you echo or return in the php file will be sent back to you jquery post. You should check out this page http://api.jquery.com/jQuery.post/ and think about using JSON formatted variables to return so like if you had this in your email script:
echo '{ "reposonse": "1" }';
This pass a variable called response with a value of 1 back to you jquery script. You could then use an if statement how you described.
just have email.php echo a 0 or 1, and then grab the data in the success event of the ajax object as follows...
$.ajax({
url: 'email.php',
success: function(data) {
if (data=="1"){
...
}else{
...
}
}
});
what you do is, you let your ajax file (email.php) print a 1 if successful and a 0 if not (or whatever else you want)
Then, in your success function, you do something like this:
function(data) {
$('form#ajax_form').slideUp('slow').before('');
if(data==1){ alert("message sent"); } else { alert("Limit exceeded"); }
$('#success').html('<h3>Success</h3>Your email is has been sent.');
}
So you capture the response in the data var of the function. If you a bigger variety in your output, you can set you dataType to "json" and have your php file print a json_encoded string so that you can access your different variables in your response via for example data.success etc.
PHP can only return to AJAX calls, by its output. An AJAX call to a PHP page is essentially the same as a browser requesting for the page.
If your PHP file was something like,
<?php
echo "1";
?>
You would receive the "1" in your JavaScript success callback,
that is,
success: function(data) {
// here data is "1"
}
As an added note, usually AJAX responses are usually done in JSON format. Therefore, you should format your PHP replies in JSON notation.

Categories