Retrieving data from ajax in php - php

I have a simple ajax call firing on click of a button, sending the element's id attribute via POST, No errors and the data is being sent, I checked on the network console.
Therefore the next logical step is to think it's an issue with the php, in which i'm making a simple update statement, the issue is the php can't see the data passed by the ajax call. please see below:
AJAX:
$("a.report_btn").click(function() {
var url = "report_post.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("a.report_btn").attr("id"),
success: function(response) {
content.html(response);
$(".liked_success").show();
}, error:function(exception){alert('Exeption:'+exception);}
});
return false; // avoid to execute the actual submit of the form.
});
PHP:
<?php include 'db_connect.php';
$id =$_POST['id'];
try {
$sql = "UPDATE jobs_list
SET post_like = post_like+1, TimeStamp = TimeStamp
WHERE id=$id
LIMIT 1";
$statement = $dbh->prepare($sql);
$statement->bindValue("id", $id, PDO::PARAM_INT);
$statement->bindValue("post_like", $_POST['post_like'], PDO::PARAM_INT);
$count = $statement->execute();
$dbh = null; // Disconnect
}catch( PDOException $e ) {
echo 'Ops... something went wrong...'; // error message
var_dump($statement);
}
?>

Related

Error handling in Ajax call (jQuery) not working

I use jQuery and Ajax to pass data to a PHP / MySQLi page.
The code and the query work as intended but I can't find a way to handle the errors.
E. g. I want to inform the user about a potential duplicate record when the data that I pass to the PHP page already exists in my database (see comment in the code below).
I tried different approaches but my error handling is always ignored or not applied.
Can someone tell me how to do this right ?
jQuery (shortened):
$('#btnSave').on('click', function(e) {
e.preventDefault();
var vid = $.trim($('#vid').val());
var vid2 = $.trim($('#vid2').val());
var vid3 = $.trim($('#vid3').val());
var mode = 'update';
if(vid == 'new') {
mode = 'insert';
}
$.ajax({
type: 'POST',
url: 'updateVid.php',
data: {
mode: mode,
vstId: vstId,
vstId2: vstId2,
vstId3: vstId3
},
success: function(result){
alert('success');
},
error: function() {
alert('error'); // I am unable to retrieve this in jQuery / Ajax resp. to do anything here
}
});
});
PHP / MySQLi (shortened):
<?php
require_once 'me/config.php';
$postData = $_POST;
$mode = $_POST['mode'];
$vid = $_POST['vid'];
$vid2 = $_POST['vid2'];
$vid3 = $_POST['vid3'];
$conn = new mysqli($host, $username, $password, $database);
if($conn->connect_error) {
die("Connection Error: " . $conn->connect_error);
}
if($mode == 'update') {
$stmt = $conn->prepare("UPDATE vids v SET v.vid2 = ?, v.vid3 = ? WHERE v.vid = ?");
$stmt->bind_param("sss", $vid, $vid2, $vid3);
$stmt->execute();
} else {
$vid = '99999999';
$vid2 = '99XXX999';
$stmt = $conn->prepare("SELECT vid2 FROM vids WHERE vid = ?");
$stmt->bind_param("s", $vid);
$stmt->execute();
$stmt->store_result();
if($stmt->num_rows > 0) {
echo 'Error'; // I am unable to retrieve this in jQuery / Ajax
} else {
$stmt->close();
$stmt = $conn->prepare("INSERT INTO vids (vsid, vid2, vid3) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $vid, $vid2, $vid3);
$stmt->execute();
echo 'Success';
}
}
$stmt->close();
$conn->close();
?>
Many thanks in advance,
Tom
It 's all about HTTP status codes. The jQuery success function is fired, when the http status code was 200/OK. If the returned http status code was errornous, it calls the error function. Knowing that you have to send http status codes within the php response header.
For this please have a look at the php http_reponse_code() function.
http_response_code(422);
echo json_encode($some_data);
exit();
Your echo output is always a valid output for jQuery. Outputting data without a status code is always a 200/OK status. As shown above, you can set the returned status with PHP. A list of HTTP status codes is shown here.
Because your AJAX call is always successful you will not get a failure. If the AJAX call fails, you will get an error.
Your PHP can fail separately, but it will not produce an AJAX error, so if you want to handle PHP errors with AJAX you have to handle them in the success function but providing a way to know the PHP failed. For example:
success: function(result){
if(result->message == 'fail') {
// handle failure here
}
},
ALSO
Please, quit using alert() for troubleshooting., use console.log() instead.

Ajax - variables are seen in chrome network tab but they don't seem to pass to the PHP function

I am trying to update a php function using ajax.
I Have an array stored in localstorage.
The array contains values of clicked id's.
When I click the <tr>, the array gets updated and sent via ajax from a js file to the php file.
js file
function storeId(id) {
var ids = JSON.parse(localStorage.getItem('reportArray')) || [];
if (ids.indexOf(id) === -1) {
ids.push(id);
localStorage.setItem('reportArray', JSON.stringify(ids));
}else{
//remove id from array
var index = ids.indexOf(id);
if (index > -1) {
ids.splice(index, 1);
}
localStorage.setItem('reportArray', JSON.stringify(ids));
}
return id;
}
//ajax function
$('table tr').click(function(){
var id = $(this).attr('id');
storeId(id);
var selected_lp = localStorage.getItem('reportArray');
console.log(selected_lp);
var query = 'selected_lp=' + selected_lp;
$.ajax({
type: "POST",
url: "../inc/updatelponadvdash.php",
data: { selected_lparr : selected_lp},
cache: false,
success: function(data) {
return true;
}
});
});
updatelponadvdash.php file
<?php
require_once 'inc.php';
$selected_lparr = json_decode($_POST['selected_lparr']);
foreach($selected_lparr as $value){
$dbData = $lploop->adv_lploops($value);
}
?>
Now, in the chrome network tab, when I click the and I dump_var($selected_lparr) the array is updated and I see the values like this:
For some reason I get a 500 error.
As well I dont understand why the var_dump(inside the function below) dosent work. I seems that the function adv_lploops dosent get the variables. but i dont understand why.
This is the fuction I call:
public function adv_lploops($value){
$sql = "SELECT * FROM `lptitels` WHERE titleidNo = '$value'";
$row = $sql->fetch(PDO::FETCH_ASSOC);
var_dump($row);
}
You aren't executing the sql query, try the following:
$sth = $db->prepare($sql);
$sth->execute();
$row = $sth->fetch(PDO::FETCH_ASSOC);
note: you will need the $db object which is a connection to your database

Why am I getting undefined index when calling a php method with AJAX?

I'm trying to get some information from my albums class. I think my issue is in the syntax of my AJAX call. Let me break this down for you step by step. Here's the method:
Album.php
...
public function getTracks ($title) {
$db = Dbclass::getDB();
$query = "SELECT *
FROM upcoming_albums_tracks
WHERE albums_title = :title";
$statement = $db->prepare($query);
$statement->bindParam(':title', $title, PDO::PARAM_STR, 50);
$statement->execute();
$tracks = $statement->fetchAll();
return $tracks;
}
This method is working fine, by the way. Now here's my php file that calls this method:
GetTracks.php
<?php
require_once '../../models/database.php';
require_once 'Album.php';
$tracks = new Album;
$tracks->getTracks($_POST['albumTitle']);
return $tracks;
And finally, the AJAX call
upcoming_albums_ajax.js
...
$(document).ready(function() {
//Get track info with Ajax
$(".btn-tracks").click(function (e) {
// stop form submission first
e.preventDefault();
// get album title
var albumTitle = $(this).val();
console.log(albumTitle) //This gives me the value I'm looking for.
// get tracks from php
$.ajax({
url : '../../controllers/admin/GetTracks.php',
//I think the issue is in how I'm formatting the data.
data: {title: albumTitle},
type : 'POST',
success : function (d) {
alert(d);
},
error : errorHandler
});
});
});
My alert just pops up telling me that I have an undefined index: albumTitle.
By the way, this is my button:
<button type='submit' class='btn-tracks' value='" . $album['albums_title'] . "'>Show Tracks</button>
In GetTracks.php you expect to receive $_POST['albumTitle']
$tracks->getTracks($_POST['albumTitle']);
But you pass in $_POST['title'] from javascript
data: {title: albumTitle},
Change either (so they're equal) and you should be fine

Catch Ajax data variables in PHP?

I'm trying to get the data used below to be caught in my alives.php page.
Essentially, alives.php requires a variable $passcode.
How do I pass the content of data below as the variable $passcode through a POST request?
<script>
$(document).ready(function() {
$('#alive').click(function () {
var data = '<?php $row['code']; ?>';
$.ajax({
type:"GET",
cache:false,
url:"alives.php",
data:data, // multiple data sent using ajax
success: function (html) {
}
});
return false;
});
});
</script>
alives.php
<?php
require("database.php");
$checkvote = "SELECT code FROM votes WHERE code = '$passcode'";
$updatealive = "UPDATE votes SET alive = +1 WHERE code = '$passcode'";
$addvote = "INSERT INTO votes (code, alive) VALUES ('$passcode',+1 )";
$checkvoterlt = mysqli_query($con, $checkvote);
if(mysqli_num_rows($checkvoterlt) > 0) {
$result = mysqli_query($con, $updatealive) or die(mysqli_error());
} else {
$result = mysqli_query($con, $addvote) or die(mysqli_error());
}
mysqli_close($con);
?>
So much is wrong.
Problem 1: You are specifying a GET request: $.ajax({ type:"GET",. If you want it to be POST:
$.ajax({
type:"POST",
Problem 2: Your javascript data variable should be key: value pairs like:
var data = { 'passcode' : code };
Then in PHP get the data with $_POST['passcode']
This sort of passcode should NOT be passed to the client side, as it can be easily manipulated.
Instead, store such information in a $_SESSION variable (assumes you've started your PHP with session_start), as this will keep the value safe, pass it to all pageloads where it may be needed, and be impossible to manipulate (while it is possible to hijack someone else's session, a malicious user still won't be able to actively change the value)

How does Ajax work with PHP?

I'm having troubles using ajax and php. What I'm trying to do is call an ajax function that grabs a value from an form's input, and checks if that email exists in a database. Here is my current javascript:
//Checks for Existing Email
function checkExisting_email() {
$.ajax({
type: 'POST',
url: 'checkExist.php',
data: input
});
emailExists = checkExisting_email();
//If it exists
if (emailExists) {
alert("This email already exists!");
}
Unfortunately, I can't get my alert to go off. In my PHP function, it checks whether the input is a username or an email (just for my purposes, and so you know), and then it looks for it in either column. If it finds it, it returns true, and if not, it returns false:
include ('func_lib.php');
connect();
check($_POST['input']);
function check($args)
{
$checkemail = "/^[a-z0-9]+([_\\.-][a-z0-9]+)*#([a-z0-9]+([\.-][a-z0-9]+)*)+\\.[a-z]{2,}$/i";
if (!preg_match($checkemail, $args)) {
//logic for username argument
$sql = "SELECT * FROM `users` WHERE `username`='" . $args . "'";
$res = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($res) > 0) {
return true;
} else {
return false;
}
} else {
//logic for email argument
$sql = "SELECT * FROM `users` WHERE `email`='" . $args . "'";
$res = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($res) > 0) {
return true;
} else {
return false;
}
}
}
SO my issue is, how does ajax respond to these returns, and how do I make ajax function accordingly? Mainly, why doesn't this work?
Any help is very much appreciated. Thank you!
You need to add the success option to your Ajax request, which is the JS function which gets executed when the XHR succeeds. Have a look at the jQuery documentation for more info.
Without running the script, I think you'll find that $_POST['input'] is empty; you need to pass your data as something like data: {'input': input} to do that.
Your PHP also needs to return some content to the script; consider changing your call to check() to something like this:
echo (check($_POST) ? 'true' : 'false');
You can now check the content in JavaScript.
Basically ajax is a hand-shaking routine with your server.
Ajax:
$.post('yoursite.com/pagewithfunction.php',
{postkey1:postvalue1, postkey2:postvalue2...},
function (response) {
// response is the data echo'd by your server
}, 'json'
);
pagewithfunction:
yourFunction(){
$var1 = $_POST['postkey1'];....
$result = dosomething($var1..);
echo json_encode($result); // this is passed into your function(response) of ajax call
}
So in $.post you have the url of the php page with the function, { var:val } is the post data, and function(response) is where you handle the data that is echo'd from your server -- the variable, response, is the content that is echo'd.

Categories