Submission condition for ajax - php

I have an html form, and an ajax script that sends it without refreshing the page, I also have a check that two identical post dates do not get into the database, but when I click on submit, it still writes "form was submitted", help me fix it
Here is my script
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$('#my_form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '/main/store',
data: $('#my_form').serialize(),
success: function () {
alert('form was submitted');
}
});
});
});
</script>
</head>

Without knowing the data you send in the ajax request or how you process the request at the server you will need to adapt the following semi-pseudo code to suit your needs or simply design your own solution using some of this.
Essentially the ajax callback should receive data from the server. In your code the callback has no arguments supplied - add a variable in success: function () {... similar to success: function(r) {... so the response from the server is now assigned to r
With that response you can now display a different message to the user based upon the value of r.
For instance:
<?php
/****************
/main/store
*/
if( $_SERVER['REQUEST_METHOD']=='POST' ){
require 'dbconn.php';
/* example pseudo function to test date */
function date_is_duplicate( $date ){
global $db; // your db connection variable
$sql='select * from `TABLE` where `DATEFIELD`=?';
$stmt=$db->prepare( $sql );
$stmt->bind_param('s',$date);
$stmt->execute();
$stmt->store_result();
$rows=$stmt->num_rows;
$stmt->free_result();
$stmt->close();
/*
..... etc, etc, etc and return a value to be used in ajax callback
If there are ZERO rows send ZERO as response - or more than ZERO means duplicate
*/
return $rows;
}
/* Do the Duplicate Date search tests */
$result=date_is_duplicate( $_POST['date'] );
if( $result ) exit( $result );
else{
/*
do other exciting things - add to db etc etc but SEND a response to the
ajax callback so that it can display the correct message.
send ZERO as response.
*/
}
}
?>
And then, the modified javascript that has a response variable that helps fork the program logic:-
$(function(){
$('#my_form').on('submit', function(e){
e.preventDefault();
$.ajax({
type: 'POST',
url: '/main/store',
data: $('#my_form').serialize(),
success:function(r) {
let message='OK, form was submitted';
if( Number(r)===1 )message='Bogus, duplicate date detected';
alert(message);
}
});
});
});
A far more robust data structure to send back would be JSON rather than a single integer - this was hastily cobbled together to illustrate the concept. With JSON you can design greater complexity into the solution

Related

Multiple Ajax call with same JSON data key calling one php file

I am trying to validate list of dynamic text fields.
Validation needs an AJAX call to interact with server.
At the backend I have written just one php file that reads the input request data and performs operation. Below is the example.
abc.js
row_count = 6
for (i = 1; i <=row_count; i++) {
id = "#val"+i.toString() ;
$(id).change(function(){
input_val="random";
$.ajax({
url:"url.php",
type:post,
async:true,
dataType: 'json',
data : {temp:input_val},
success:function(result){},
error: function (request, status, error) {}
});
});
}
url.php
<?php
$random_val = $_POST['temp'];
$cmd = 'systemcommand '.$random_val;
$flag = exec($cmd);
if ($flag == 0){
echo json_encode(array("status"=>'Fail'));
}
else{
echo json_encode(array("status"=>'Success'));
}
?>
It works fine when the row_count = 1 (Just one text field) but fails when the input is more than 1.
When the count is more than 1, the php script is not able to read the request data(The key in JSON data "temp"). it is blank in that case.
Any lead or help should be appreciated.
Thanks
Your javascript bit needs some adjusting, because you do not need to define an ajax for every single element. Use events based on a class. Also, since input behave differently than select, you should setup two different event class handlers.
function validateAjax ( element ) {
var input_val = element.val();// get the value of the element firing this off
$.ajax({
url: "url.php",
type: 'post',
async: true,
dataType: 'json',
data : { temp: input_val },
success: function(result) {
// check your result.status here
},
error: function (request, status, error) { }
});
}
$(".validate_change").on("change",function() { // for selects
validateAjax( $(this) );
});
$(".validate_input").on("input",function() { // for text inputs
validateAjax( $(this) );
});
And for your select or input you add that appropriate class.
<select class="validate_change" name="whatever"><options/></select>
<input class="validate_input" name="blah">
PS
I really worry about this code you have:
$cmd = 'systemcommand '.$random_val;
$flag = exec($cmd);
So, you are just executing anything that is coming in from a webpage POST var??? Please say this website will be under trusted high security access, and only people using it are trusted authenticated users :-)

Compare user value to database and show result through ajax jquery

Guys m working on my first live project and i am stuck at a point, where i need help with ajax jquery. i can do this with PHP but i wanna do this with ajax.
Here if user enter a product code ,so i want to compare this product code value into my database and show product name in my other form ,which will open after user input value:
Here in first field i want product name:
Here in my table you can see product code and product name:
ok so here is my html code in last option when user enter product code
Here is jquery i am sending user data to 8transectiondata.php to compare
And this is php file and i want $data['product_name']; to show
Here's a generic answer.
JS FILE:
$(document).ready(function () {
$('#myButtonId').on('click', function () {
var code = $('#myCodeInputId').val();
if (code !== '') { // checking if input is not empty
$.ajax({
url: './my/php/file.php', // php file that communicate with your DB
method: 'GET', // it could be 'POST' too
data: {code: code},
// code that will be used to find your product name
// you can call it in your php file by "$_GET['code']" if you specified GET method
dataType: 'json' // it could be 'text' too in this case
})
.done(function (response) { // on success
$('#myProductNameInput').val(response.product_name);
})
.fail(function (response) { // on error
// Handle error
});
}
});
});
PHP FILE:
// I assumed you use pdo method to communicate with your DB
try {
$dbh = new PDO('mysql:dbname=myDbName;host=myHost;charset=utf8', 'myLogin', 'myPassword');
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
exit('ERROR: ' . $e->getMessage());
}
$sql = "SELECT `product_name` FROM `products` WHERE `product_code` = :code";
$result = $dbh->prepare($sql);
$result->bindValue('code', $_GET['code'], PDO::PARAM_INT);
$result->execute();
if($result->rowCount()) { // if you got a row from your DB
$row = $result->fetchObject();
echo json_encode($row, JSON_UNESCAPED_UNICODE); // as we use json method in ajax you've got to output your data this way
// if we use text method in ajax, we simply echo $row
}
else {
// handle no result case
}
I know what you want to do, but without specific code the best I can do is give you a generalized answer.
When a user fills out a field, you want to post that field to the server, look up a product and return some stuff.
The basics are going to look like this.
$(document).ready( function(){
//rolling timeout
var timeout;
$('#field').on('keyup', function(e){
if(timeout) clearTimeout(timeout);
timeout = setTimeout( function(){
var data = {
"field" : $('#field').val()
};
$.post( '{url}', data, function(response){
if(response.debug) console.log(response.debug);
if(response.success){
//open other form
$('{otherFormProductField}').val(response.product);
}
}); //end post
},450); //end timeout
});//end onKeyup
}); //end onReady
Then in PHP, you have to process the request. Pull the field from the $_POST array, look it up in the Database. Then build a response array and send it back to the client as JSON. I like to build responses in a structure something like this.
{
success : "message", //or error : "message"
debug : "",
item : ""
}
Then in PHP I will do this.
ob_start();
..code..
$response['debug'] = ob_get_clean();
header("Content-type:application/json");
echo json_encode($response);
This way, you can still print out debug info (in side the output buffer calls ) when developing it and don't have to worry about it messing up the Json or the header call.
-note- Use a timeout, that you reset on each key press (a rolling timeout). What it does is reset the previous timeout each time the key is released. That way it only sends the request once the user quits typing (instead of sending request on every keypress). I have found 450 milliseconds to be about the perfect value for this. Not too long not too short. Basically once they stop typing for 450ms it will trigger the $.post

How to send data from one page to another and upon success show a modal

This is my page from where I want to send data to dashboard/fpass.php page and upon success show a modal.
<script>
$(document).ready(function () {
$('#fmodal').click(function () {
$.ajax({
type: "POST",
url: "dashboard/fpass.php",
data: { name: "fpass" }
})
success: function(data) {
$("#myModal").modal();
}
});
});
</script>
And here is my next page where I want to get my data and send a mail.
<?php
if(($_POST['name'])=='fpass')
{
/*add sql connection*/
require('../includes/dbconfig.php');
/*get the image file name from the table*/
$sql="select * from admin";
$res=mysqli_query($con,$sql);
$row=mysqli_fetch_array($res);
$email=$row['email'];
$password=$row['password'];
$bemail=$row['bemail'];
$sub="dashboard login password is < ".$password." >";
/*send mail to the sql entry*/
mail($email,"Forget Password Request",$sub,$bemail);
}
?>
Try changing your AJAX:
<script>
$(document).ready(function(){
$('#fmodal').click(function(){
var name = 'fpass';
$.ajax({
type: "POST",
url: "dashboard/fpass.php",
data: { name: name },
success: function(data) {
$("#myModal").modal('show');
}
});
});
});
</script>
Man, the problem that I see is in the receiving code. AJAX needs to get some response from that file, you are not sending anything back, that's why. When you execute the mail() function, if CORRECT, then return true, 1 or any message that you want referring to the successful operation.
Try this:
if (mail($email,"Forget Password Request",$sub,$bemail))
echo true; //or echo 1, something referring to successful execution
else {
/**
* If you want to use the error{} part of the AJAX, you need to send different headers
* header('HTTP/1.1 500 Internal Server Error');
*/
// And then the echo, or just the echo is fine if you want to use it in the success section
echo false; // or echo 0, somtehing referring to a failed execution
}
In the AJAX side, you get the response, and evaluate if is true or false and then you decide what to do.
Hope that can help. J.C!
Your JS code is not valid. Have a look here, to see how $.ajax(...) is used:

Why doesn't the die() function work?

I have an ajax call that sends data from a form to a php file that will then insert that data to the database. I put a call to die in said php file because I want to try something but it doesn't work.
addUserForm.php
<script>
$(document).ready(function () {
var $form = $('form');
$form.submit(function (event) {
event.preventDefault();
var formData = $form.serialize(),
url = $form.attr('action');
$.ajax({
type: "POST",
url: url,
data: formData,
success: function () {
//$("#div1").load("table.php");
alert('User Successfully Added');
document.getElementById("form1").reset();
}
});
});
});
</script>
Here is the php file:
addUser.php
<?php
include('sqlconnection.php');
die('here');
$firstname = $_POST['fname'];
$lastname = $_POST['lname'];
$middlename = $_POST['mname'];
$password = $_POST['pword'];
$username = $_POST['uname'];
$gender = $_POST['gender'];
$utype = $_POST['utype'];
$query = "INSERT INTO user (firstname,lastname,middlename,gender) VALUES ('$firstname','$lastname','$middlename','$gender')";
mysqli_query($con,$query);
$result = mysqli_query($con,"SELECT id FROM user WHERE firstname = '$firstname'");
$row = mysqli_fetch_assoc($result);
$uid=$row['id'];
$result = mysqli_query($con,"INSERT INTO accounts (u_id,username,password,account_type) VALUES ('$uid','$username',md5('$password'),'$utype');");
?>
Even when there is a die call in adduser.php it still alerts that the user was successfully added.
That's because die() only terminates/ends the PHP script. From an AJAX point of view the request was successful.
You should echo the info in the PHP page and then output the content of the response in your AJAX.
You could also set the response header in your PHP Script to something other than 200/OK, such as 401/Unauthorized or 400/Bad Request. Basically all 400 and 500 status codes indicate error.
Since the PHP code executes successfully even thou die(), the ajax will trigger the success and you will recevie the success message.
to stop your javascript at any point you can add return false;
In your success block
success: function () {
//$("#div1").load("table.php");
alert('User Successfully Added');
document.getElementById("form1").reset();
}
You can add these two line like this
success: function (data) {
/* These two lines*/
console.log(data);
return false;
//$("#div1").load("table.php");
alert('User Successfully Added');
document.getElementById("form1").reset();
}
So once you're done with your debugging you can remove those lines..
Die function doesn't stop javascript. It just stop PHP.
For exemple, if you add the die() function before inserting datas, datas will not be inserted but the success funciton will be executed and you will have alert.
If you want to execute the Error function, you have to add Throw exception or header 403 in the php file.
The jQuery success function just make sure the page is loaded. A die in PHP doesn't change that. You will have to check with returned data.
success
Type: Function( PlainObject data, String textStatus, jqXHR jqXHR )
A function to be called if the request succeeds. The function gets passed three arguments: >The data returned from the server, formatted according to the dataType parameter; a string >describing the status; and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object. As of jQuery >1.5, the success setting can accept an array of functions. Each function will be called in >turn. This is an Ajax Event.
ajax request php file, die ('here') is equivalent to echo 'here', return value, that successful implementation

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.

Categories