ajax success not getting php records - javascript

I am trying to get my db rows from php. Currently the js success function isn't being reached. Is there anything obvious in the php that may be causing an issue?
The php
$id=$_GET['id'];
$stmt = $db->prepare("SELECT * FROM brand_members WHERE Id = :id");
$stmt->bindValue(':id',$id,PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($result);
The js
$.ajax({
url: 'dead.php', //the script to call to get data
data: "id=8",
dataType: 'json', //data format
success: function(data) //on recieve of reply
{
var id = data[0]; //get id
var vname = data[1]; //get name
alert("a"); //get name
}
});

The problem is you didn't passed properly your $_GET parameter
To solve that
Change your
url: 'dead.php'
to
url: 'dead.php?id=8',
also data: your_data is no longer needed
Or this method change
data: "id=8"
to
data: {id: 8}
Also in your callback since your ajax response returns an array specified the index 0
success: function(data) //on recieve of reply
{
var id = data[0]['Id']; //get id
var vname = data[0]['name']; //get name
alert("a");
}

Related

How to GET javascript data in PHP file without page reload

I am building my best attempt at a twitter clone and have run into a bit of a problem. I want to be able to click on a post and, without a page refresh, display that post in the overlay of the page (as you would on a twitter feed to look at replies, etc.).
In script.js, I check for a click and try to change the url.
$('body').on("click", ".chirp", function(){
var uid = $_GET['id'];
var pid = $(this).attr("id");
var pidSplit = pid.split("chirp");
var messageID = pidSplit[1];
var obj = {foo: "status"};
$('.chirpOverlay').addClass("active");
window.history.pushState(obj, "Status", "profile.php?id="+uid+"&status="+pid);
});
The javascript works as intended...but as I will soon find out, the victory is short-lived.
In profile.php, I attempt to GET the status id from the URL parameter.
<?php
$status_id = $_GET['status'];
$sql = $db->query("SELECT * FROM chirps WHERE id='$status_id'");
if (mysqli_num_rows($sql) > 0) {
$c = $sql->fetch_object();
}
?>
This doesn't work because, as I've learned, using 'window.history.pushState' only changes the url- but doesn't load the page. Thus the $_GET statement fails. I need a way to get the id of the post I click on into profile.php without a page refresh. Even if it means taking a different approach (instead of using a URL parameter).
PS: I tried to do an XMLHttpRequest as well- to no avail. :(
Thanks in advance!
$('body').on("click", ".chirp", function(){
var uid = $_GET['id'];
var pid = $(this).attr("id");
var pidSplit = pid.split("chirp");
var messageID = pidSplit[1];
var obj = {foo: "status"};
$('.chirpOverlay').addClass("active");
$.ajax({
url: "profile.php?id="+uid+"&status="+pid,
type: "GET",
data: obj,
dataType: "html",
success: function(data){
console.log(data);
}
});
});
You need to just get something up and going that works and then you can add more to it as you figure things out. This should give you a good starting place.
Here are your two files. Make sure they are both in the same directory.
You will need to make sure you have a jquery version loaded. Put this on whatever page you are calling the script.js from.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
script.js
$(document).ready(function(){
$('body').click(function(){
var id; //define your id.
var pid; //define your pid.
var datastring = 'id=' + uid + '&status=' + pid;
console.log(datastring);
$.ajax({
url: 'profile.php',
type: 'POST',
cache: false,
data: datastring,
dataType: 'json',
success: function(data){
console.log('Made it to the success function: ' + data);
if (data) {
//It works, do something.
console.log(data);
} else{
//It does not work, do something.
console.log('Your ajax failed to get the info from your php page. Keep troubleshooting');
}
}
});
});
});
profile.php
<?php
/*
$status_id = $_POST['status']; //This needs to be sanitized and validated.
$sql = $db->query("SELECT * FROM chirps WHERE id='$status_id'"); //This is unsafe sql practice.
if (mysqli_num_rows($sql) > 0) {
$c = $sql->fetch_object();
}
echo json_encode($c); //This is what gets sent back to script.js
*/
echo 'You made it to your php page.';
?>
A few things:
You can not call any php variable from within your js. var uid = $_GET['id']; does not work.
Any value that you pass to the php page needs to be validated to make sure it is a legitimate value.
Your SQL query is prone to sql injections. Please read up on how to parameterize your queries. Good Mysqli Practices
I have finally found a AJAX-based solution to my problem.
I created a new php file called "chirp_open_ref.php" and added this ajax to script.js:
var datastring = 'status=' + messageID;
$.ajax({
url: "chirp_open_ref.php",
type: "POST",
data: datastring,
cache: false,
dataType: "text",
success: function(data){
$('.chirp-container').html(data);
}
});
Inside of 'chirp_open_ref.php':
<?php
require 'core.inc.php';
if (isset($_POST['status']) && isset($_SESSION['user_id'])){
$chirp_id = $_POST['status'];
$c = "";
$sql = $db->query("SELECT * FROM chirps WHERE id='$chirp_id'");
if (mysqli_num_rows($sql) > 0){
$c = $sql->fetch_object();
}
include'chirp.inc.php';
}
?>
'chirp.inc.php' is simply a template for the layout/structure of each post.
This works like a charm, but I am always open to any criticism of how I am performing this. Thanks for all the help guys!

Javascript and PHP. Sending Multiple Array to PHP Using Ajax and Convert it to PHP Array

I need some help. I am trying to send multiply array of width and length to php, straight forward. I don't want to save it to any HTML field, however it's not working. I am getting the width and length from html text are and convert it to a number and then add it to an array in javascript.
Here is the code for that
var widthL = [];
var lengthL = [];
var widths = document.wall.width.value;
var lengths = document.wall.length.value;
var wNumber = Number(widths);
var lNumber = Number(lengths);
widthL.push(JSON.stringify(wNumber));
lengthL.push(JSON.stringify(lNumber));
This is the Ajax code I am using to send it to PHP
$.ajax( {
type: "POST",
url: "./Summary.php",
data: {"widths": widthL, "lengths" : lengthL},
cache: false,
success: function (response) {
console.log("This is the width", widthL, " This is the length", lengthL);
}
});
In PHP I am using this code to receive it. But I am not getting things back.
<?php
$lengths = json_decode($_POST['lengths']);
$widths = json_decode($_POST['widths']);
echo 'This is the width: '.$widtsL;
echo 'This is the length: '.$lengths;
?>
I was hopping that someone could help me out here.
First you should specify the content type in the ajax POST:
$.ajax( {
type: "POST",
url: "./Summary.php",
contentType: "application/json; charset=UTF-8", // Add content type
data: {"widths": widthL, "lengths" : lengthL},
cache: false,
success: function (response) {
console.log("This is the width", widthL, " This is the length", lengthL);
}
});
then in PHP:
$request_body = file_get_contents('php://input'); //This reads the raw POST data
$json = json_decode($request_body); // Then parse it to JSON
$lengths = $json->lengths;
$widths = $json->widths;
please add a POST parameter name as dataType,type it value JSON,
the Ajax data param value use key=value&key=value format
then in php file enter debug code

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'].

Ajax Post Value not being passed to php file

I am having problems passing the variable to the php page.
Here is the code below:
var varFirst = 'something'; //string
var varSecond = 'somethingelse'; //string
$.ajax({
type: "POST",
url: "test.php",
data: "first="+ varFirst +"&second="+ varSecond,
success: function(){
alert('seccesss');
}
});
PHP:
$first = $_GET['first']; //This is not being passed here
$second = $_GET['second']; //This is not being passed here
$con=mysqli_connect("localhost","root","pass","mydb");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"INSERT INTO mytable (id, first, second) VALUES ('', $first, $second)");
mysqli_close($con);
}
I'm I missing something? The actual data is saving to the database BUT $first and $second value is not being passed to the php file.
You are using the POST type, retrieve it in POST :
$first = $_POST['first'];
$second = $_POST['second'];
Or change your JQuery call :
$.ajax({
type: "GET",
url: "test.php",
data: "first="+ varFirst +"&second="+ varSecond,
success: function(){
alert('seccesss');
}
});
This is appening because your are passing data throw POST method and try to get with GET so change those two lines
$first = $_POST['first']; //This is not being passed here
$second = $_POST['second']; //This is not being passed here
Or simply change your method to GET in your jquery
type: "GET"
You are using type: "POST" in ajax and trying to fetch using $_GET, try
$first = $_REQUEST['first']; //This is not being passed here
$second = $_REQUEST['second'];
And there is a method to pass data like that
$.ajax({
type: "POST",
url: "test.php",
data: {first: varFirst,second: varSecond},
success: function(){
alert('seccesss');
}
});
And there you can use
$_POST['first'];
$_POST['second'];
Hope it helps.

Ajax call insert

I have 2 ajax calls one to insert data, one to get data. Together with the functions for select and insert. the console log of the ajax call select is empty. However, when i check phpmyadmin the correct value is there.
If i start the game again, there will be 1 value (from previous game) but the score of the actual game isn't there. Until I start the game again. And so on. Does anyone know why the values are in my sql but the ajax call says it's empty?
What I understand from it. There's a score via ajax and in php it will get into the part "Check json" it sees json isn't empty so it goes to InsertScore().
The second ajax is cast but this time it doesn't have json so it will get to the method "GetScores".
The insert happens always before the select so the last score should be seen, I don't understand why it doesn't do that.
Ajax call insert:
$.ajax({
type: "POST",
url: "Database.php",
dataType: "json",
data: { json: jsonData }
});
ajax call select:
$.ajax({
url: "Database.php",
type: "POST",
dataType: "json",
success: function (obj) {
console.log(obj);
stageRef.$("txtTopscorePunt").html(obj[0].Score);
stageRef.$("txtTopscoreNaam1").html(obj[0].Naam);
stageRef.$("txtTopscorePunt2").html(obj[1].Score);
stageRef.$("txtTopscoreNaam2").html(obj[1].Naam);
stageRef.$("txtTopscorePunt3").html(obj[2].Score);
stageRef.$("txtTopscoreNaam3").html(obj[2].Naam);
}
});
php insert:
function InsertScore($obj) {
$query = "INSERT INTO topscoresNew (Score, Naam) VALUES('" . $obj['score'] . "','" . $obj['naam'] . "')";
$result = mysql_query($query);
}
php select:
function GetScores() {
$query = "SELECT * FROM topscoresNew ORDER BY Score DESC LIMIT 3";
$result = mysql_query($query);
$scoresArray = array();
$i = 0;
while ($row = mysql_fetch_assoc($result)) {
$scoresArray[$i]['Score'] = $row['Score'];
$scoresArray[$i]['Naam'] = $row['Naam'];
$i++;
}
echo json_encode($scoresArray);
}
check json:
if (isset($_POST['json'])) {
$score = json_decode($_POST['json'], true);
InsertScore($score);
} else {
GetScores();
}
Make the ajax-calls synchronous:
$.ajax({
type: "POST",
url: "Database.php",
dataType: "json",
data: { json: jsonData },
async: false
});
This way the 'select'-call will wait for the 'insert'-call to finish.

Categories