Unable to pass variable value to ajax from php - php
My ajax:
$("document").ready(function(){
$(".form").submit(function(){
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "response.php", //Relative or absolute path to response.php file
data: data,
success: function(data) {
//$(".the-return").html("<br />JSON: " + data["json"] );
// alert("Form submitted successfully.\nReturned json: " + data["json"]);
alert(data);
// window.location='success.php'
}
});
return false;
});
});
I declared a variable to store unique_id like this:
$unique_id=uniqid();
I'm inserting data like this:
try
{
$stmt2 = $pdo->prepare('INSERT INTO usrinfo (UUID,Name,Phone,Email,Postcode,DateReg,Reputation,ReviewPlus,ReviewNeg,Sex,Status,IsTuitionCentre) VALUES(:uuid,:name,:phone,:email,:poscode,now(),:reputation,:reviewplus,:reviewneg,:sex,:status,:permission)');
$stmt2->execute(array(
':uuid' => $unique_id,
':name'=>$name,
':phone'=>$phone,
':email'=>$email,
':poscode'=>$postcode,
':reputation'=>78,
':reviewplus'=>65,
':reviewneg'=>3,
':sex'=>$gender,
':status'=>0,
':permission'=>$permission
));
# Affected Rows?
echo $stmt2->rowCount(); // 1
} catch(PDOException $e) {
echo 'Error: ' . $e->getMessage();
}
Now, I want to pass the above unique_id to ajax page but couldn't.
echo $unique_id;
It just doesn't alert anyting, but:
$abc="123";
echo $abc;
this shows the alert box with value 123!
Why is it so? WHy I coudn't pass unique_id value like this?
MY ENTIRE PHP SCRIPT:
<?php
//Function to check if the request is an AJAX request
if (is_ajax()) {
if (isset($_POST["action"]) && !empty($_POST["action"])) { //Checks if action value exists
$action = $_POST["action"];
switch($action) { //Switch case for value of action
case "test": test_function(); break;
}
}
}
//Function to check if the request is an AJAX request
function is_ajax() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
function test_function(){
include($_SERVER['DOCUMENT_ROOT'].'/config.php');
$return = $_POST;
$return["json"] = json_encode($return);
//below code to store in database
$data = json_decode($return["json"], true);
/*....salting starts........*/
/*..........salting ends..............*/
echo $unique_id=uniqid();
$name=$data['name'];
$phone=$data['phone'];
$email=$data['email'];
$postcode=$data['postcode'];
$a=$data['sub'];
$b=$data['rate2'];
$subject_rate = array_intersect_key($b,$a);
/*...pdo.............................*/
$username="root";
$password="";
try {
//$pdo = new PDO('mysql:host=localhost;dbname=users', $username, $password);
//$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
include($_SERVER['DOCUMENT_ROOT'].'/config.php');
$stmt = $pdo->prepare('INSERT INTO authsessions (email,useruuid,salt,hashpword) VALUES(:email,:useruuid,:salt,:hash)');
$stmt->execute(array(
':email' => $email,
':useruuid'=>$unique_id,
':salt'=>$salt,
':hash'=>$hash
));
# Affected Rows?
$stmt->rowCount(); // 1
} catch(PDOException $e) {
'Error: ' . $e->getMessage();
}
//query2
try
{
$stmt2 = $pdo->prepare('INSERT INTO usrinfo (UUID,Name,Phone,Email,Postcode,DateReg,Reputation,ReviewPlus,ReviewNeg,Sex,Status,IsTuitionCentre) VALUES(:uuid,:name,:phone,:email,:poscode,now(),:reputation,:reviewplus,:reviewneg,:sex,:status,:permission)');
$stmt2->execute(array(
':uuid' => $unique_id,
':name'=>$name,
':phone'=>$phone,
':email'=>$email,
':poscode'=>$postcode,
':reputation'=>78,
':reviewplus'=>65,
':reviewneg'=>3,
':sex'=>$gender,
':status'=>0,
':permission'=>$permission
));
# Affected Rows?
$stmt2->rowCount(); // 1
} catch(PDOException $e) {
'Error: ' . $e->getMessage();
}
//query3
try
{
$stmt3 = $pdo->prepare('INSERT INTO tutoravailability (uuid,week_morning,week_afternoon,week_evening,weekend_morning,weekend_afternoon,weekend_evening) VALUES(:uuid,:week_morning,:week_afternoon,:week_evening,:weekend_morning,:weekend_afternoon,:weekend_evening)');
$stmt3->execute(array(
':uuid' => $unique_id,
':week_morning'=>$week_morning,
':week_afternoon'=>$week_afternoon,
':week_evening'=>$week_evening,
':weekend_morning'=>$weekend_morning,
':weekend_afternoon'=>$weekend_afternoon,
':weekend_evening'=>$weekend_evening
));
# Affected Rows?
$stmt3->rowCount(); // 1
} catch(PDOException $e) {
'Error: ' . $e->getMessage();
}
//query4
foreach($subject_rate as $v=>$k)
{
$key=$v;
$value=$k;
$post_unique_id= uniqid();
try
{
$stmt4 = $pdo->prepare('INSERT INTO posts (PostUUID,subid,date,pricing,post_status,UUID,Name,Phone,Email,Poscode,DateReg,Reputation,ReviewPlus,ReviewNeg,Sex,week_morning,week_afternoon,week_evening,weekend_morning,weekend_afternoon,weekend_evening,Status) VALUES(:PostUUID,:subid,now(),:pricing,:post_status,:UUID,:Name,:Phone,:Email,:Poscode,now(),:Reputation,:ReviewPlus,:ReviewNeg,:Sex,:week_morning,:week_afternoon,:week_evening,:weekend_morning,:weekend_afternoon,:weekend_evening,:Status)');
$stmt4->execute(array(
':PostUUID' => $post_unique_id,
':subid'=>$key,
':pricing'=>$value,
':post_status'=>1,
':UUID'=>$unique_id,
':Name'=>$name,
':Phone'=>$phone,
':Email' =>$email,
':Poscode'=>$postcode,
':Reputation'=>78,
':ReviewPlus'=>65,
':ReviewNeg'=>3,
':Sex'=>$gender,
':week_morning'=>$week_morning,
':week_afternoon'=>$week_afternoon,
':week_evening'=>$week_evening,
':weekend_morning'=>$weekend_morning,
':weekend_afternoon'=>$weekend_afternoon,
':weekend_evening'=>$weekend_evening,
':Status'=>0
));
# Affected Rows?
$stmt4->rowCount(); // 1
} catch(PDOException $e) {
'Error: ' . $e->getMessage();
}
}
/*try
{
$sql = "SELECT *FROM authsessions WHERE useruuid =:uid";
$statement = $pdo->prepare($sql);
$statement->bindValue(':uid', $unique_id);
$statement->execute();
$json = array();
while( $row = $statement->fetch()) {
array_push($json, array("id" => $row['useruuid']));}
header('Content-Type: application/json');
echo json_encode($json);
} catch(PDOException $e) {
echo 'Error: ' . $e->getMessage();
}*/
// $unique_id=uniqid();
}
?>
You need to use json_encode because the AJAX call says dataType: "json".
echo json_encode($unique_id);
It worked when you echoed 123 because a decimal number is valid JSON. But uniqid returns a hex string, and this isn't valid JSON. You need to encode it with quotes around it.
Related
php ajax request don't give any response or error
I've been trying to grab a username based on registered email when user enters his email and click on a button I've provide two data to my ajax request first is [cf] which identify which portion of code should be processed and second is the email but when clicking the button nothing happens and no errors appear in the console only when I open the page that have the php code of ajax request it says "Notice: Undefined variable: funcCall in D:\XAMPP\htdocs\lahj\framework\signin.php on line 19" Here I will provide my code for ajax: $("#login-next-btn").click(function(){ if(!$("#signin-email").val().trim()){ var email = $("#signin-email").val().trim(); $.ajax({ url: "framework/signin.php", type: "POST", data: {cf:'cf1',email:email}, dataType:"json", success: function(data){ if(data.result != "0") { alert("helo"); $("#signin-box-header p:first-of-type").text("مرحبًا"); $("#signin-box-header p:last-of-type").remove(); $("#signin-box-header").append("<p id='sigin-email-display'>"+data.result+"</p>"); $("#first-loader").fadeOut(600,function(){ $("#second-loader").css({"display":"flex"}).fadeIn(400); }); } else { alert("fail"); } } }); } }); and here is my php code in a file called signin.php in a folder called framework: <?php ini_set( 'error_reporting', E_ALL ); ini_set( 'display_errors', true ); include_once 'db.php'; $email = null; $funcCall = null; if(isset($_POST['email'])) { $email = $_POST['email']; } if(isset($_POST['cf'])) { $funcCall = $_POST['cf']; } if($funcCall == 'cf1' && !empty($email)) { try { $database = new db(); $db = $database->openConnection(); $stmt = $db->prepare("select userName from khUsers where email = ?"); $stmt->execute(array($email)); $usersName = $stmt->fetchColumn(); $data = array('result' => $usersName); echo json_encode($data); } catch (PDOException $e) { echo "There is some problem in connection: " . $e->getMessage(); $data = array('result' => "0"); echo json_encode($data); } } ?>
Add exit() function at the end of json_encode() function. it will show you result/error on your request in console. if($funcCall == 'cf1' && !empty($email)) { try { $database = new db(); $db = $database->openConnection(); $stmt = $db->prepare("select userName from khUsers where email = ?"); $stmt->execute(array($email)); $usersName = $stmt->fetchColumn(); $data = array('result' => $usersName); echo json_encode($data); exit(); } catch (PDOException $e) { echo "There is some problem in connection: " . $e->getMessage(); $data = array('result' => "0"); echo json_encode($data); exit(); } }
Display search result in another page
Here is my api code for search data by pin code: function findPlace(){ $request = \Slim\Slim::getInstance()->request(); $pinCode = json_decode($request->getBody()); try { if(1){ $vendorSearchData = ''; $db = getDB(); $sql = "SELECT vendor_name,logo,phone_no FROM vender_list WHERE post_code LIKE :post_code"; $stmt = $db->prepare($sql); $stmt->bindParam("post_code", $pinCode, PDO::PARAM_STR); $stmt->execute(); //echo "<pre>"; print_r($stmt); echo"</pre>";die; $vendorSearchData = $stmt->fetchAll(PDO::FETCH_OBJ); $db = null; if($vendorSearchData) echo '{"vendorSearchData": ' . json_encode($vendorSearchData) . '}'; else echo '{"vendorSearchData": ""}'; } else{ echo '{"error":{"text":"No access"}}'; } } catch(PDOException $e) { echo '{"error":{"text":'. $e->getMessage() .'}}'; } } Here is the file, where I call function to find data. If its true, then will navigate to another page, but on that page I get blank page: findPlace(searchVal){ this.authService.postData(this.vendorSearchPostData, "findPlace") .then((result) => { this.responseData = result; if (this.responseData.vendorSearchData) { this.dataSet = this.responseData.vendorSearchData; this.navCtrl.push(SearchResultPage, { data: searchVal}); } else { let toast = this.toastCtrl.create({ message: "No data Found", duration: 2000 }); toast.present(); } }, (err) => { }); } How display the search result on another page?
Update SQL Database with JavaScript
I am trying to update my database through a JS Function. After googling for a while I understood that it is clearly not possible without using AJAX. So it is my first time and I tried, here is my JS code: $("#update").click(function(event){ var showArr = document.forms['ownForm'].elements['showArr'].value; $.ajax({ url: './../pages/updateDatabase.php', type: 'POST', data: { showArr: showArr } , success: function( msg ) { alert( "Data Saved: " + msg ); } }); return false; }); and my PHP file: <?php try { $conn = new PDO('mysql:host=localhost;dbname=+++', '+++', ''); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sql = "UPDATE Users SET SHOWARR = true WHERE ID = 1"; $stmt = $conn->prepare($sql); $stmt->execute(); echo $stmt->rowCount() . " records UPDATED successfully"; } catch(PDOException $e) { echo $sql . "<br>" . $e->getMessage(); } $conn = null; ?> But nothing happens! Where is my mistake?
Your URL in ajax function does not look right:- give the full URL like this url:'http://yourdomain.com/page.php'; I hope it works
Notification appears to be successful even if no data has been added to database
So I have these codes wherein I want a notification to appear in every event. I want to check if the record exists, then a notification will appear, saying the college already exists. But that doesn't happen tho. I keep on inputting duplicate input, but the notification still says it's successful. Is there a mistake in my code? add-college.php <?php function findDuplicate($code) { try { include($_SERVER['DOCUMENT_ROOT']."/config/db-config.php"); $sql = "SELECT * FROM colleges WHERE collegecode = ?"; $stmt = $conn->prepare($sql); $stmt->bind_param("s", $code); $stmt->execute(); $stmt->store_result(); if ($stmt->num_rows > 0) { return true; } else { return false; } } catch (Exception $e) { return false; } } try { include($_SERVER['DOCUMENT_ROOT']."/config/db-config.php"); $code = $_POST['code']; $name = $_POST['name']; $result = array(); if (findDuplicate($code)) { $result['message'] = 'duplicate'; } else { $sql = "INSERT INTO colleges(collegecode, collegename) VALUES(?, ?)"; $stmt = $conn->prepare($sql); $stmt->bind_param("ss", $code, $name); if ($stmt->execute()) { $result['message'] = 'success'; } else { $result['message'] = 'error'; } } echo json_encode($result); } catch (Exception $e) { echo json_encode($result); } ?> script.js $("#save-new").click(function() { var form = $("#add-college"); var code = $("#code").val(); var name = $("#name").val(); $.ajax({ type: "POST", data: { code: code, name: name }, url: "../ajax/add-college.php", dataType: "html", success: function(data) { if (data.message = "success") { $.notify({ // options message: 'College has been added.' },{ // settings type: 'success' }); } else if (data.message = "duplicate") { $.notify({ // options message: 'College already exists.' },{ // settings type: 'warning' }); } else { $.notify({ // options message: 'College cannot be added.' },{ // settings type: 'error' }); } $("#code").val(""); $("#name").val(""); $("#add-new").modal('hide'); showColleges(); } }); });
data.message = "success" this is assignment operation, if you want to compare two string use == operator. So, the correct statement would be for the if condition would be if(data.message == "success") Similarly, if(data.message == "duplicate"). I am sure you are aware of all this!
Return PHP error handling with AJAX
I have a page powered with PHP and AJAX, when a user submits one of my forms I check for errors in the getData.php script. This example is if the user submits the form with the default value I'm wondering if there is a way to pass back those errors or trigger the AJAX to fire an error if the user commits on or if I need to do error handling before the AJAX call $('form').on('submit', function (e) { e.preventDefault(); $.ajax({ type: 'post', url: '_ajax/addData.php', data: $('form').serialize(), success: function () { $("input").val('Info Here'); $("form").hide(); reloadInfo(); } }); }); PHP $info = $_POST['info']; if($info != 'Info Here') { $conn = mysqli_connect(); $query = "INSERT INTO leads VALUES(0, '$companyName', 1, NOW(), 3)"; $result = mysqli_query($conn, $query) or die ('Error Could Not Query'); $id = mysqli_insert_id($result); header("Location: http://localhost/manage/info.php?id=$id"); mysqli_close($conn); } else { echo '<script>alert("Error");/script>' } PART 2
Javascript: success: function (data) { if(!data.success) alert(data.errors); // Just for demonstration purposes $("input").val(data.errors); $("form").hide(); reloadInfo(); } PHP: header("Content-Type: text/json; charset=utf8"); if($info != 'Info Here') { $conn = mysqli_connect(); $query = "INSERT INTO leads VALUES(0, '$companyName', 1, NOW(), 3)"; $result = mysqli_query($conn, $query) or die ('Error Could Not Query'); $id = mysqli_insert_id($result); header("Location: http://localhost/manage/info.php?id=$id"); mysqli_close($conn); } else { echo json_encode(array("success" => false,"error" => "Some random error happened")); }
There are several issues with your code: $companyName is not defined anywhere You should use prepared statements instead of throwing data into your SQL query You should put your entire AJAX PHP code inside one try..catch block At the end of your AJAX PHP code, write something some JSON I don't get why you are trying to redirect an AJAX call, usually you'd tell the client to do the redirect. For example, I would write your PHP code like so: try { if(!isset($_POST['info'])) throw new Exception('Post info was not set'); $info = $_POST['info']; if($info == 'Info Here') throw new Exception('Invalid value for info'); $conn = mysqli_connect(); if(!$conn) throw new Exception('Database connection failure'); $companyName = '?????'; $query = 'INSERT INTO leads VALUES(0, ?, 1, NOW(), 3)'; $stmt = mysqli_prepare($query); if(!$stmt) throw new Exception('Could not query database'); mysqli_stmt_bind_param($stmt, 's', $companyName); mysqli_stmt_close($stmt); $id = mysqli_stmt_insert_id($stmt); mysqli_close($conn); echo json_encode(array( 'success' => true, 'new_id' => $id, )); }catch(Exception $ex){ echo json_encode(array( 'success' => false, 'reason' => $ex->getMessage(), )); }
Alternate Approach HTML: place this paragraph tag where you want to display an error. <p id="display_error"></p> Ajax success call: change your Ajax code bit like... success: function(response) { if((response !== "") && ($.isNumeric(response))) { { //redirect in ajax success location.href = "http://localhost/manage/info.php?id="+ response; } else { //this will display the custom error. $("#display_error").html("<p>" + response + "</p>"); //output: something went wrong! } } PHP $info = $_POST['info']; if($info != 'Info Here') { $conn = mysqli_connect(); $query = "INSERT INTO leads VALUES(0, '$companyName', 1, NOW(), 3)"; $result = mysqli_query($conn, $query) or die ('Error Could Not Query'); $id = mysqli_insert_id($result); echo $id; //header("Location: http://localhost/manage/info.php?id=$id"); mysqli_close($conn); } else { echo 'something went wrong!'; }