I have a small problem, which is that when I add my prepared statement into the PHP file, the Ajax stops working and gives me a 500- error, but when I remove the statement, it works like a charm.
This is my PHP file:
<?php
include ('db_connect.php');
include ('functions.php');
$datad = $_POST['superstr'];
$id = 1;
$stmt = $mysqli->prepare("UPDATE `song` SET `lyrtext`=? WHERE `id`=?");
$stmt->bind_param("si", $datad, $id);
$status = $stmt->execute();
echo $datad;
?>
and my Ajax looks like this:
$.ajax({
url: 'includes/sendlyrics.php',
type: 'POST',
data: {superstr: 'pelle'},
success: function(data) {
//called when successful
var hello = data;
//prompt(data);
console.log("The data is:");
console.log(data);
console.log("The variable which should keep the data has this content:");
console.log(hello);
},
error: function(e) {
//called when there is an error
console.log(e.message);
prompt(e.message);
//alert(e.message);
}
});
What's the problem?
$stmt = $mysqli->prepare("UPDATE `song` SET `lyrtext`=? WHERE `id`=?");
$stmt->bind_param("si", $datad, $id);
$status = $stmt->execute();
Is wrong. Amend this to:
$stmt = $mysqli->prepare("UPDATE `song` SET `lyrtext`=? WHERE `id`=?");
$stmt->bind_param("si", $datad, $id);
$stmt->execute();
If you are looking for confirmation of the query executing successfully you can test this by:
if($stmt->execute()){
//returned true - statement executed successfully
} else{
//returned false
}
Also you should modify your Ajax call to something similar to:
$.ajax({
url : "your/url/here.php"
type : "POST",
data : {superstr: 'pelle'},
dataType : "json",
success : function(data){
//do something with the response
},
error : function(jqXHR, textStatus, errorThrown){
//handle the error
}
});
By adding a dataType of json, you should then ammend the echo statement of your .php file to read:
$response = Array();
array_push($response, $datad);
echo json_encode($response);
I'm sure you've read the documentation online already, but Ajax can be found here, and prepared statements here.
This is all written with the caveat that your DB connection is valid...which it would appear to be given the wording of your question, and your previous attempts at solving the issue.
Related
I submit a php form using jquery ajax, but when receive a parameter value of callback function success, the parameter value contains enter key in front of the value returned from the server.
The work around, I use includes method.
Does anyone know why the enter key inserted in front of the value returned from the server?
$.ajax({
type: "POST",
url: "_action.php",
data: dataString,
success: function(result) {
n = result.includes("success");
if (n) {
grecaptcha.reset();
$("#spinner-contact").remove();
$('#success_msg').html("<img class='img-fluid aligncenter mb-3' id='checkmark' src='media/img/form_submitted.jpg' />");
}
else {
grecaptcha.reset();
$("#spinner-contact").remove();
$('#success_msg').html("<div class='mt-3'><strong><h1 class='alert alert-warning'>Contact failed!</strong> Please submit again.</h1></div>");
}
}
});
$statement = runQPs("INSERT INTO my_guestbook(title, url, path, pos, content, isactive, date) VALUES(
?, ?, ?, ?, ?, ?, ?
)",[$name, $email_from, $address, $telephone, $comments, 0, $now]);
// Insert contact success or fail
if($statement->affected_rows === 0) {
$result = "fail";
}
else {
$result = "success";
}
echo $result;
In PHP code you can return value like that:
return json_encode(result);
In JS file:
success: function(result) {
// this will be your response from PHP code
// add you'r IF statement here
console.log(result);
}
i think, u can change your "echo" in php file to return "json"
and in your ajax code:
n = result.includes("success");
to
var response = result.message(name of return json);
After echo the result variable you can die the statement something like that.
echo $result;die;
or
die($result);
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.
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);
}
?>
I have the following PHP script:
include("dbconnecti.php");
$cropId = $_POST['cropId'];
//echo 'the id is: ' . $cropId;
$query = "SELECT W.*,FI.*, PN.*, CONCAT(FI.fName, ' ', FI.lname) AS farmer
FROM `wantToSell` AS W, `produceName` AS PN, `farmerInfo` AS FI
WHERE W.farmerId = FI.farmerId AND W.produceId = PN.produceId AND W.produceId = '" . $cropId ."'";
$result = $dbconnect->query($query);
if($result){
while($row = $result->fetch_assoc()){
$allRows[] = $row;
}
echo json_encode($allRows);
}
else{
echo json_encode($dbconnect -> error);
die;
}
}
And JQuery script:
function cropDescrip(clicked_id) {
$.ajax({
url : "../php/cropdescrip.php",
type : "POST",
dataType : 'JSON',
cache : false,
data : {cropId : clicked_id},
success : function (data) {
console.log(data);
} //end success
}); //end ajax
} //end cropDescrip
If I replace $_POST[cropId] with a actual value (e.g. tmt001) the query statement returns a valid result. But when I pass a value to $_POST[cropId] via a jQuery Ajax call, the SQL query returns an empty set.
The echo statement shows that the value is being passed to the PHP script.
What is happening, and how do I fix it?
Perhaps it would be best to change your code to use a prepared statement. It might solve your problem as well as removing your sql injection risk. Something like this:
$stmt = $mysqli->prepare("SELECT W.*,FI.*, PN.*,
CONCAT(FI.fName, ' ', FI.lname) AS farmer
FROM `wantToSell` AS W, `produceName` AS PN, `farmerInfo` AS FI
WHERE W.farmerId = FI.farmerId AND W.produceId = PN.produceId AND W.produceId =?";
/* assuming cropId is a string given your quotes in the original */
$stmt->bind_param("s", $cropId);
/* execute query */
$stmt->execute();
$result = $stmt->get_result();
Just guessing here, but it looks like you're passing the clicked_id of the element, and not the value of that element. Try this from your jQuery code:
function cropDescrip(clicked_id) {
$.ajax({
url : "../php/cropdescrip.php",
type : "POST",
dataType : 'JSON',
cache : false,
data : {cropId : $("#" + clicked_id).val()}, // <-- HERE
success : function (data) {
console.log(data);
} //end success
}); //end ajax
} //end cropDescrip
This will find the element with the id, using element_id as the selector value. It will capture the value of that element, and pass it through the cropId key to the PHP server.
If this doesn't work as-is, it would be very useful to know precisely what clicked_id actually is (show the HTML and Javascript code for it), and what value is being passed to the PHP server in $_POST[cropId].
I'm a newbie in AJAX and i tried to make a simple MySQL query in AJAX but it doesn't work, the response is a 500 Internal Server error.
I searched for the answer on this forum and other websites but i've never found an answer for my problem.
Basically, on my app, the user writes a pseudo and click on 'play', and an AJAX function is called onClick, a function that make a simple MySQL query :
$.ajax({
url: "check_pseudo.php",
method: "GET",
data : { pseudo : input},
error: function() {
alert("Une erreur est survenue");
},
success: function(response) {
alert(response);
}
});
PHP / MySQL :
$pseudo = $_GET["pseudo"];
$req = $bdd->prepare('SELECT ? FROM pseudo');
$req->execute(array($pseudo));
$reponse = $req->fetch();
if ($reponse) {
echo "This pseudo does exist";
}else{
echo "Pseudo not found";
}
This code sends me 'GET http://localhost:8888/check_pseudo.php?pseudo=oianf 500 (Internal Server Error)' in the console debugger.
How could i solve this problem?
Merci :)
You can't do this:
$req = $bdd->prepare('SELECT ? FROM pseudo');
$req->execute(array($pseudo));
Using prepare() with a ? in it builds a query expecting additional input. You need to fill that ? with something. (check out PHP's mysqli::prepare).
You need to do something like:
$req = $bdd->prepare('SELECT ? FROM pseudo');
$req->bind_param("s", $pseudo);
$req->execute();
...but even that doesn't quite seem right. Usually we wouldn't be passing the fields to be selected inside query params. We would usually do something like this:
$.ajax({
url: "users.php",
method: "GET",
data : {user_id: input_id},
error: function() {
alert("Error! ...Something went wrong.");
},
success: function(response) {
alert(response);
}
});
Then inside users.php we would have:
$user_id = $_GET["user_id"];
$req = $bdd->prepare('SELECT * FROM users where user_id=?');
$req->bind_param("i", $user_id);
$req->execute();
$reponse = $req->fetch();
if ($reponse) {
echo "This user does exist";
} else {
echo "User not found";
}