How to send response from PHP to Ajax? - javascript

This JavaScript code uses POST method to send data from form to PHP where PHP checks in database if data is true. But I don't know how to send response from PHP back to JS that fetching was successful. Can someone explain?
JS:
$('#submit-btn').on('click', function() {
var dataString = 'username=' + document.getElementById('username').value + '&password=' + document.getElementById('password').value + '&rememberMe=' + document.getElementById('rememberMe').value;
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
data: dataString,
cache: false,
success: function(){
//check if what response is
}
});
ajaxsubmit.php:
<?php
session_start();
//connect
$username =$_POST['username'];
$password =$_POST['password'];
$sql = "SELECT * FROM user WHERE email ='$username' OR username ='$username' AND password = '$password'";
$result = mysqli_query($conn, $sql);
if(!$row = mysqli_fetch_assoc($result)){
//response error
} else{
//response success
}
?>

Whatever you echo out in the php will be sent back to the ajax.
if(!$row = mysqli_fetch_assoc($result)){
echo 0;
}
else{
echo 1;
}
success: function(response){
//check if what response is
console.log( response );
}

You have to echo something in your PHP to get something returned:
if(!$row = mysqli_fetch_assoc($result)){
//response error
echo 'there is a problem';
} else {
//response success
echo 'yippee!';
}
Then you can log the return as follows:
$('#submit-btn').on('click', function() {
var dataString = 'username=' + document.getElementById('username').value + '&password=' + document.getElementById('password').value + '&rememberMe=' + document.getElementById('rememberMe').value;
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
data: dataString,
cache: false,
success: function(data){ // 'data' is the variable holding the return from PHP's echo
//check if what response is
console.log(data);
}
});
Make sure to watch the AJAX request / response in the browser's developer tools. Make sure you included the jQuery library in the project. The console will reveal errors. AJAX requires a web server.
WARNING Little Bobby says your script is at risk for SQL Injection Attacks. Learn about prepared statements for MySQLi. Even escaping the string is not safe!
DANGER Never store plain text passwords! Please use PHP's built-in functions to handle password security. If you're using a PHP version less than 5.5 you can use the password_hash() compatibility pack. It is not necessary to escape passwords or use any other cleansing mechanism on them before hashing. Doing so changes the password and causes unnecessary additional coding.

You can exit method with response parameters. like:
ajaxsubmit.php
if(!$row = mysqli_fetch_assoc($result)){
exit('error'); //exit with response 'error'
} else{
exit('success'); //exit with response 'success'
}
JS
$('#submit-btn').on('click', function() {
var dataString = 'username=' + document.getElementById('username').value + '&password=' + document.getElementById('password').value + '&rememberMe=' + document.getElementById('rememberMe').value;
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
data: dataString,
cache: false,
success: function(response){
//check if what response is
console.log(response);
}
});

Related

Ajax Data Returning Undefined Object

The jquery is going to a .php to retrive data, and it is successfully retriving information, but the information is returning as undefined when placed on a page.
var userId = $("#userid").val();
$(function()
{
$.ajax({
url: "../apipages/getprofilecomment.php?userId=${userId}",
method: "GET",
type: "json",
cache: false,
success: function(comment){
$('#usercommentdiv').append("<li>" + comment.user_name + ':' + comment.profile_comment + ',' + comment.time_added + "</li>");
}
});
});
This is the .php page that is returning the data:
<?php
include ("../db/database.php");
include ("../classes/profilecommentclass.php");
include ("../classes/userclass.php");
session_start();
$userId = $_SESSION['user_id'];
$userClassHandler = new User($db, $userId);
$profileCommentHandler = new ProfileComment($db);
$userNameData = $userClassHandler->getUserName();
$profileComment = $profileCommentHandler->getAllFromComment(34);
$profileCommentArray = array(
"userName" => $_SESSION["user_name"],
"user_profile_comment" => $profileComment["profile_comment"],
"time_added" => $profileComment["time_added"],
"time_updated" => $profileComment["time_updated"]
);
echo json_encode($profileCommentArray);
?>
This is what is being returned at: apipages/getprofilecomment.php?userId=${userId}
{"userName":"Acidify","user_profile_comment":"Working to get this app running!!!","time_added":"2019-12-14 00:51:04","time_updated":"15:00:00"}
Note: No particular concerned with the user_name being null.
Change type: "json" to dataType: "json" in the ajax setup and the parse will occur automatically

PHP not catching data from Ajax Jquery

Im trying to pass data from using Ajax and PHP on server side. the php file is not catching the data sent through Ajax.
the code gets the values with jquery and make a long string called data
the jquery code looks like this:
var data = 'ppemail=' + $('#email').val()
+ '&monto_enviar=' + montoEnviarDisp
+ '&monto_pub=' + montoPubDisp
+ '&tasa=' + tasaDisp
+ '&monto_recibir=' + monto_recibirDisp
+ '&banco=' + $('#banco').val()
+ '&receptor=' + $('#receptor').val()
+ '&cuenta=' + $('#cuenta').val()
+ '&cedula=' + $('#cedula').val();
$.ajax({
type: "POST",
url: 'crear_oferta.php',
data: ({data}),
success: function (response) {
alert(response);
}
});
the php file is this:
<?php
session_start();
require_once 'dbconfig3.php';
var_dump($_POST);
try {
$userID = $_SESSION['userSession'];
$ppemail = $_POST['ppemail'];
$monto_e = $_POST['monto_enviar'];
$monto_p = $_POST['monto_pub'];
$tasa = $_POST['tasa'];
$monto_rec = $_POST['monto_recibir'];
$banco = ($_POST['banco']);
$receptor = ($_POST['receptor']);
$cuenta = ($_POST['cuenta']);
$cedula = ($_POST['cedula']);
/// luego de confirmar hacer el try e insertar
//if(isset($_POST['btnferta'])){
//$password = md5($upass);
$bid_date = date('Y-m-d H:i:s');
$stmt = $db_con->prepare("INSERT INTO ofertas(uid,email_pp,nombre_receptor,banco_receptor,cuenta_receptor,cedula_receptor,monto_enviar,monto_publicar,tasa,monto_recibir,fecha)
VALUES(:userid, :emailpp, :nombre, :banco, :cuenta, :cedula, :monto_e, :monto_p, :tasa, :monto_r, :fecha)");
$stmt->bindParam(":userid", $userID);
$stmt->bindParam(":emailpp", $ppemail);
$stmt->bindParam(":nombre", $receptor);
$stmt->bindParam(":banco", $banco);
$stmt->bindParam(":cuenta", $cuenta);
$stmt->bindParam(":cedula", $cedula);
$stmt->bindParam(":monto_e", $monto_e);
$stmt->bindParam(":monto_p", $monto_p);
$stmt->bindParam(":tasa", $tasa);
$stmt->bindParam(":monto_r", $monto_rec);
$stmt->bindParam(":fecha", $bid_date);
$stmt->execute();
echo 'ok';
} catch (PDOException $ex) {
echo $ex->getMessage();
}
?>
why the $_POST is not getting any data? Thanks for the help!
You should set data to an object. This ensures that the URL parameters will be properly encoded; otherwise, you need to call encodeURIComponent on any parameter that could contain special characters.
var data = {
'ppemail': $('#email').val(),
'monto_enviar': montoEnviarDisp,
'monto_pub': montoPubDisp,
'tasa': tasaDisp,
'monto_recibir': monto_recibirDisp,
'banco': $('#banco').val(),
'receptor': $('#receptor').val(),
'cuenta': $('#cuenta').val(),
'cedula': $('#cedula').val()
};
Then you shouldn't wrap it in another object when calling $.ajax:
$.ajax({
type: "POST",
url: 'crear_oferta.php',
data: data,
success: function(response) {
alert(response);
}
});
It looks like you're trying to pass a string as an object property. Change your $.ajax options:
$.ajax({
type: "POST",
url: 'crear_oferta.php',
data: data,
success: function(response) {
alert(response);
}
});

Send variable to php via ajax

I'm trying to send a input value to php via ajax but I can't seem to get this right. I'm trying to create a datatable based on the user input.
This is my code:
<input class="form-control" id="id1" type="text" name="id1">
My javascript code:
<script type="text/javascript">
$(document).ready(function() {
var oTable = $('#jsontable').dataTable(); //Initialize the datatable
$('#load').on('click',function(){
var user = $(this).attr('id');
if(user != '')
{
$.ajax({
url: 'response.php?method=fetchdata',
data: {url: $('#id1').val()},
dataType: 'json',
success: function(s){
console.log(s);
oTable.fnClearTable();
for(var i = 0; i < s.length; i++) {
oTable.fnAddData([
s[i][0],
s[i][1],
s[i][2],
s[i][3],
s[i][4],
s[i][5],
s[i][6],
s[i][7]
]);
} // End For
},
error: function(e){
console.log(e.responseText);
}
});
}
});
});
</script>
My php script:
<?php
$conn = pg_connect(...);
$id1 = $_POST["id1"];
$result = pg_query_params($conn, 'SELECT * FROM t WHERE id1 = $1 LIMIT 20', array($id1));
while($fetch = pg_fetch_row($result)) {
$output[] = array ($fetch[0],$fetch[1],$fetch[2],$fetch[3],$fetch[4],$fetch[5],$fetch[6],$fetch[7]);
}
echo json_encode($output);
?>
I don't know a lot of js but my php is correct i test it. So i guess the problem is in the javascript code.
The problem is, my datatable is not being created based on the user input.
Thank you!
change
data: {url: $('#id1').val()},
to:
type: 'POST',
data: {id1: $('#id1').val()},
However the problem might be bigger. You might not be getting the correct data from PHP. You can debug by adding the error option to your ajax() call, like this:
$.ajax({
url: 'response.php?method=fetchdata',
type: 'POST',
data: {id1: $('#id1').val()},
dataType: 'json',
success: function(s){
},
error: function (xhr, status, errorThrown) {
console.log(xhr.status);
console.log(xhr.responseText);
}
});
Then check your browser's Console for the output, this should give you some type of error message coming from PHP.
My assumption is that since you are using dataType: 'json', the ajax request expects JSON headers back, but PHP is sending HTML/Text. To fix, add the correct headers before echoing your JSON:
header('Content-Type: application/json');
echo json_encode($output);

How to avoid 500 Internal Server Error if a JS session variable null

I created this script to read from various web sources. This script updates all notifications (mail, post, friends) and their own drop-down window's details and also two side update bars together. I used this script in my top manu.php page.
This script is working well for login user.
Now I pass a session id variable with JavaScript var uid = '<? echo $session->id; ?>'; So when a user is not logged in, my browser console displays 500 Internal Server Error because here the session has no ID so it passes uid= ''
How do I overcome this problem?
Here is my JavaScript script:
var uid = '<? echo $session->id; ?>';
function addmailno(type, msg){
//Do something for display mail/friend/post notification
}
function addmailup(type, msg){
//Do something for display mail/post/friend drop-down.
}
function addside(type, msg){
//Do something for display all friend/new post in side bar.
}
function waitFormailno(){
$.ajax({
type: "GET",
url: "serverforupandside.php",
cache: false,
async : false,
dataType : 'json',
data: "uid="+ uid,
timeout:15000,
success: function(data){
addmailno("MyDivClass", data);
addmailup("MyDivClass", data);
addside("MyDivId", data);
setTimeout(waitFormailno, 15000);
},
error: function(){
setTimeout(waitFormailno, 15000);
}
});
}
$(document).ready(function(){
waitFormailno();
});
serverforupandside.php
<?php
include("db.php");
include_once("mysession.php");
while (true) {
if($_GET['uid']){
global $dbh;
//All php query is here one after one
//Output is here by data
$data = array();
$data['upmail'] = $upmail;
$data['upfollow'] = $upfollow;
$data['uppost'] = $uppost;
// etc all
if (!empty($data)) {
echo json_encode($data);
flush();
mysqli_close($dbh);
}
}
mysqli_close($dbh);
}
?>
Your Javascript code should be modified to:
function waitFormailno(){
$.ajax({
type: "GET",
url: "serverforupandside.php",
cache: false,
async : false,
dataType : 'json',
data: "uid="+ uid,
timeout:15000,
success: function(data){
addmailno("MyDivClass", data);
addmailup("MyDivClass", data);
addside("MyDivId", data);
}
});
}
$(document).ready(function(){
setInterval(waitFormailno, 15000); // calls a function or evaluates an expression at specified intervals (in milliseconds)
});
PHP Code:
<?php
include("db.php");
include_once("mysession.php");
if (!empty($_GET['uid'])) {
global $dbh;
//All php query is here one after one
//Output is here by data
$data = array();
$data['upmail'] = $upmail;
$data['upfollow'] = $upfollow;
$data['uppost'] = $uppost;
// etc all
if (!empty($data)) {
echo json_encode($data);
}
}
Also, you should add validations before filling $data array.

Retrieving values from an Ajax post in PHP

I submitting a form by using an ajax request which posts values to a php script which then stores those values in a database. This is my ajax post:
$.ajax({
type:"POST",
url: "wp-content/plugins/super-plugin/process.php",
'data': 'datastring',
success: function() {
$('#formwrapper').html("<div id='message'></div>");
$('#message').html("<h2>Contact form submitted!</h2>")
.append("<p>We will be in touch soon.</p>").hide().fadeIn(1500, function() {
$('#message').append("<img id='checkmark' src='images/check.png' />");
});
}
});
And this is my PHP file:
$full = explode("&", $_POST["data"]);
$fname = explode(":", $full[0]);
$name = $fname[1];
$femail = explode(":", $full[1]);
$email = $femail[1];
$fphone = explode(":", $full[2]);
$phone = $fphone[1];
$conn = mysqli_connect("localhost", "Andrew", "Change0", "plugindatadb");
mysqli_query($conn, "INSERT INTO data (Name, Email, Phone) VALUES ('$name', '$email', '$phone')");
The data in datastring is formatted by "name:Bo&email:bob#mail&phone:0786754333". However for some reason I can't use those variables sent in my php script? For some reason the php script does not run as well.
You mentioned that you set formatted query params in variable datastring, then in that case, you should use that like shown below in ajax request (remove quotes for data and datastring).
$.ajax({
type:"POST",
url: "wp-content/plugins/super-plugin/process.php",
data: datastring,
success: function() {
$('#formwrapper').html("<div id='message'></div>");
$('#message').html("<h2>Contact form submitted!</h2>")
.append("<p>We will be in touch soon.</p>").hide().fadeIn(1500, function() {
$('#message').append("<img id='checkmark' src='images/check.png' />");
});
}
});
remove '' from datastring ,
data: datastring
bt this is not proper way to pass data pass into json like data ,
$.ajax({
type:"POST",
url: "wp-content/plugins/super-plugin/process.php",
'data': {
name:"Bo",email:"bob#mail",phone:"0786754333"
},
success: function() {
$('#formwrapper').html("<div id='message'></div>");
$('#message').html("<h2>Contact form submitted!</h2>")
.append("<p>We will be in touch soon.</p>").hide().fadeIn(1500, function() {
$('#message').append("<img id='checkmark' src='images/check.png' />");
});
}
});
and into php page.
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
Firstly, in:
'data': 'datastring',
If "datastring" is a variable, as indicated by your description of it's format, those values shouldn't be in quotes. So:
data: datastring,
Secondly, if your PHP script assumes that the data passed in can be split into various components and it accesses those array elements without first verifying that the data is in the required format (or at least that those array elements exist) then it will throw an exception if the data is invalid. This is currently happening because the data is 'datastring'. You should always validate input parameters as it saves time in the long run.
Change the data in ajax call as
data : { datastring : datastring },
In php access it like $_POST['datastring'].

Categories