A form i'm using with a single input uses AJAX to post to the server. I plan to take the input's value which is a string and check if the string already exists in the database. I'll us in_array() and if the string doesn't exist insert it to the database and echo 1 or else 0 if it's a duplicate, sending back 1 or 0 as a result.
In my AJAX i'm using this simple function on success, if the result returns 1 i'll use jQuery to display a success message, or else i'll display an error and exit. Is this a good method to validate server side and not have the form submit by returning 1 or 0 and exit(); for duplicates?
success: function(result)
{
if(result == 1)
{ string was inserted to db }
else
{
duplicate exists
exit();
}
Thanks
I would have personally made it so in the php, I return a json encoded identity array with some of the information about the response. I usually include more information than needed, for debugging purposes and possible future changes.
if($results >= 1){
$duplicate_exists = 'true';
}elseif($results < 1){
$duplicate_exists = 'false';
};
$result = array(
'exists' => $duplicate_exists ,
'status' => $status,
'time' => time()
// etc
);
echo json_encode($result)
Then to decode the json into an object in javascript:
success: function(result){
result = jQuery.parseJSON(result)
// you can also use eval(result) , but it's much slower.
if(result.exists == 'false'){
// string was inserted to db
}else{
// duplicate exists
exit();
}
You can use the below code using AJAX and JS to post and retrieve the result.
$.ajax({
url: 'https://api.github.com/gists',
type: 'POST',
dataType: 'json',
data: JSON.stringify(data)
})
.success( function(e) {
res = jQuery.parseJSON(e);
if(res.exists == 'false'){
// string was inserted to db
}
else if(res.exists == 'true'){
// duplicate exists
exit();
}
})
.error( function(e) {
//there was error
});
Related
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.
I got following problem.
I wrote an ajax request,my PHP file does some checks and returns either an array which i echo with json_encode() or a normal echo. It depends on what is the result of the checks my PHP file makes. My problem is following:
When i give my Ajax request dataType: "json" it seems that it is only working if i return some json_encode($array) from my PHP file. If i echo normal data the Jquery won't work.
A little example:
$.ajax(
{
type: "get",
dataType: "json",
url: "check_basket.php",
data: {bought : bought, pid : pid, cid : cid, csid : csid, lang : lang},
success: function(data){
if(data.status == '1'){
alert(data.b);
} else if(data.status == '2'){
alert(data.b);
} else {
$("#dropdown_shopping_cart_inner").html(data);
$('#head_shopping_cart').load(document.URL + ' #head_shopping_cart');
$('#dropdown_shopping_cart').slideDown(800);
}
}
}
);
In my PHP i say something like this:
if(get_date_last_purchased($pid) == true){
$arr = array('status' => 1, 'b' => 'test1');
echo json_encode($arr);
}
elseif($bought > $row0['gm_max_order']){
$arr = array('status' => 2, 'b' => 'test2');
echo json_encode($arr);
} else {
echo "everything ok";
}
If one of the frist two cases happens and status 1 or 2 get returned to my JQuery, everything works fine. But when the third PHP condition happens and my PHP just returns echo without json_encode, the Jquery simply does nothing.
Any suggestions?
In your example, you explicitly request a json.
Try the shorter notation to be able to work with either data type
$.get("check_basket.php",function(data){
//Do whatever you want to do with your data
}
But your problem is, that you're mixing different types together... Any endpoint should only return the same data type and the same format, so instead I'd recommend oyu changing your PHP
if(get_date_last_purchased($pid) == true){
$arr = array('status' => 1, 'b' => 'test1');
echo json_encode($arr);
}
elseif($bought > $row0['gm_max_order']){
$arr = array('status' => 2, 'b' => 'test1');
echo json_encode($arr);
} else {
echo json_encode(array('status'=>0));
}
and change your jQuery code like this:
$.ajax(
{
type: "get",
dataType: "json",
url: "check_basket.php",
data: {bought : bought, pid : pid, cid : cid, csid : csid, lang : lang},
success: function(data){
if(data.status == 1){
alert(data.b);
} else if(data.status == 2){
alert(data.b);
} else if(data.status == 0 ) {
$("#dropdown_shopping_cart_inner").html(data);
$('#head_shopping_cart').load(document.URL + ' #head_shopping_cart');
$('#dropdown_shopping_cart').slideDown(800);
}
}
}
);
also, when checking for status 2, you're checking data == 2 instead of data.status == 2
Combine this with the short get statement, clean up your code, and you should be fine with this:
$.get('check_basket.php',function(data){
switch(data.status){
case 0:
$("#dropdown_shopping_cart_inner").html(data);
$('#head_shopping_cart').load(document.URL + ' #head_shopping_cart');
$('#dropdown_shopping_cart').slideDown(800);
break;
case 1:
alert(data.b);
break;
case 2:
alert(data.b);
break;
}
});
or even shorter:
$.get('check_basket.php',function(data){
if(data.status == 0){
$("#dropdown_shopping_cart_inner").html(data);
$('#head_shopping_cart').load(document.URL + ' #head_shopping_cart');
$('#dropdown_shopping_cart').slideDown(800);
} else{
alert(data.b);
}
});
You have two choices.
Client Side: Remove the dataType: "json" from there.
Server Side: Add json_encode("$output") here. Also you can send an empty or null value wrapped inside [], because jQuery executes it as a script.
For a solution in Server Side, I would say:
echo '["everything ok"]';
Remove the dataType altogether and let jQuery figure it out.
Construct your return messages properly to handle both success and failures also.
Assign status codes from 10 to 20 for success and from 0 to 9 for failures
For success
print json_encode(array(
'status' => 11,
'message' => "all is good"
);
For failure or error
print json_encode(array(
'status' => 4,
'message' => "some things are not so cool"
));
Adjust your success callback to handle both types of return
success: function(data){
// check if you have a success or failure
if (data.status > 10){
console.log(data.message);
}
else {
alert(data.message);
}
}
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.
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).
I've been trying to figure out what I have done wrong but when I use my JavaScript Console it shows me this error : Cannot read property 'success' of null.
JavaScript
<script>
$(document).ready(function() {
$("#submitBtn").click(function() {
loginToWebsite();
})
});
</script>
<script type="text/javascript">
function loginToWebsite(){
var username = $("username").serialize();
var password = $("password").serialize();
$.ajax({
type: 'POST', url: 'secure/check_login.php', dataType: "json", data: { username: username, password: password, },
datatype:"json",
success: function(result) {
if (result.success != true){
alert("ERROR");
}
else
{
alert("SUCCESS");
}
}
});
}
</script>
PHP
$session_id = rand();
loginCheck($username,$password);
function loginCheck($username,$password)
{
$password = encryptPassword($password);
if (getUser($username,$password) == 1)
{
refreshUID($session_id);
$data = array("success" => true);
echo json_encode($data);
}
else
{
$data = array("success" => false);
echo json_encode($data);
}
}
function refreshUID($session_id)
{
#Update User Session To Database
session_start($session_id);
}
function encryptPassword($password)
{
$password = $encyPass = md5($password);
return $password;
}
function getUser($username,$password)
{
$sql="SELECT * FROM webManager WHERE username='".$username."' and password='".$password."'";
$result= mysql_query($sql) or die(mysql_error());
$count=mysql_num_rows($result) or die(mysql_error());
if ($count = 1)
{
return 1;
}
else
{
return 0;;
}
}
?>
I'm attempting to create a login form which will provide the user with information telling him if his username and password are correct or not.
There are several critical syntax problems in your code causing invalid data to be sent to server. This means your php may not be responding with JSON if the empty fields cause problems in your php functions.
No data returned would mean result.success doesn't exist...which is likely the error you see.
First the selectors: $("username") & $("password") are invalid so your data params will be undefined. Assuming these are element ID's you are missing # prefix. EDIT: turns out these are not the ID's but selectors are invalid regardless
You don't want to use serialize() if you are creating a data object to have jQuery parse into formData. Use one or the other.
to make it simple try using var username = $("#inputUsername").val(). You can fix ID for password field accordingly
dataType is in your options object twice, one with a typo. Remove datatype:"json", which is not camelCase
Learn how to inspect an AJAX request in your browser console. You would have realized that the data params had no values in very short time. At that point a little debugging in console would have lead you to some immediate points to troubleshoot.
Also inspecting request you would likely see no json was returned
EDIT: Also seems you will need to do some validation in your php as input data is obviously causing a failure to return any response data
Try to add this in back-end process:
header("Cache-Control: no-cache, must-revalidate");
header('Content-type: application/json');
header('Content-type: text/json');
hope this help !
i testet on your page. You have other problems. Your postvaribales in your ajax call are missing, because your selectors are wrong!
You are trying to select the input's name attribute via ID selector. The ID of your input['name'] is "inputUsername"
So you have to select it this way
$('#inputUsername').val();
// or
$('input[name="username"]').val();
I tried it again. You PHP script is responsing nothing. Just a 200.
$.ajax({
type: 'POST',
url: 'secure/check_login.php',
dataType: "json",
data: 'username='+$("#inputUsername").val()+'&password='+$("#inputPassword").val(),
success: function(result) {
if (result.success != true){
alert("ERROR");
} else {
alert("HEHEHE");
}
}
});
Try to add following code on the top of your PHP script.
header("Content-type: appliation/json");
echo '{"success":true}';
exit;
You need to convert the string returned by the PHP script, (see this question) for this you need to use the $.parseJSON() (see more in the jQuery API).