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);
Related
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 form where the user has to enter their reservation id and last name. If these two values match in the database then I need to return the corresponding values from the database.
So far, everything seems to work. The correct values are being retrieved from the database. I would like to show the values inside paragraphs. I am just not sure how to archive that. ValidateReservation gets called once the button is clicked.
Here is my code:
<p id='guest_full_name'></p>
<p id='unit_number'></p>
<p id='floor'></p>
<script>
function validateReservation(){
var reservation_id = document.getElementById("reservation_id").value;
var guest_last_name = document.getElementById("guest_last_name").value;
$.ajax({
type: 'POST',
url: 'test06.php',
// dataType: 'json',
data: {
'reservation_id': reservation_id,
'guest_last_name' : guest_last_name
},
success: function(json) {
console.log(json);
$('#reservation_id').val(json.reservation_id);
$('#guest_last_name').val(json.guest_last_name);
$('#guest_full_name').val(json.guest_full_name);
$('#unit_number').val(json.unit_number);
$('#floor').val(json.floor);
$('#key_sa').val(json.key_sa);
},
error: function(err) {
console.log(err);
} }); }
test06.php
<?php
$conn = mysqli_connect("","","","");
$reservation_id=$_POST['reservation_id'];
$guest_last_name=$_POST['guest_last_name'];
$stmt = $conn->prepare("SELECT reservation_id, guest_last_name, guest_full_name, unit_number, floor, key_sa FROM reservations2 INNER JOIN guest ON (reservations2.reservation_id=guest.reservation_idg) INNER JOIN unit USING (unit_id) WHERE reservation_id=? AND guest_last_name=?");
$stmt->bind_param("ss", $reservation_id, $guest_last_name);
$stmt->execute();
$stmt->bind_result($reservation_id, $guest_last_name, $guest_full_name, $unit_number, $floor, $key_sa);
if ($stmt->errno) {
die("Query failed to execute: " . $stmt->error);
}
if ($stmt->fetch()) {
echo json_encode(array("reservation_id" => $reservation_id,
"guest_last_name" => $guest_last_name,
"guest_full_name" => $guest_full_name,
"unit_number" => $unit_number,
"floor" => $floor,
"key_sa" => $key_sa));
} else {
echo "No matching rows returned.";
}
$stmt->close();
?>
Please use .html() instead of .val()
$('#guest_full_name').html(json.guest_full_name);
$('#unit_number').html(json.unit_number);
$('#floor').html(json.floor);
You can also use the below code without jQuery
document.getElementById('guest_full_name').innerHTML = json.guest_full_name;
document.getElementById('unit_number').innerHTML = json.unit_number;
document.getElementById('floor').innerHTML = json.floor;
UPDATE:
Convert your response into json object in success function,
var json = JSON.parse(json);
I'm using jQuery with Ajax to submit a form to a PHP script.
The user will input their details, click a submit button, the PHP script will run and will have either performed the desired action or failed.
At this point I would want to display a success or error message based on the type of error.
<script>
$( "#contact-form" ).submit(function(event) {
event.preventDefault();
$.ajax({
url: "includes/contact-us.php",
type: "post",
data: $("#contact-form").serialize(),
success:function(data) {
alert(data);
},
error:function(){
alert("failure");
}
});
});
</script>
So in my jQuery above, when the form is submitted, it prevents the default action="path to script.php" then performs the submit. I've done this in case users have Javascript disabled, so at least the base functionality will be there.
PHP
<?php
if(isset($_POST['contact']) && !empty($_POST['contact'])){
$link = new mysqli("example", "example", "example", "example");
if($link->connect_errno > 0) {
die('Unable to connect to database [' . $link->connect_error . ']');
}
$name = $_POST['name'];
$email = $_POST['email'];
$website = $_POST['website'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$stmt = $link->prepare("INSERT INTO contact (name, email, website, subject, message) VALUES (?, ?, ?, ?, ?)");
$stmt->bind_param("sssss", $name, $email, $website, $subject, $message);
if($stmt->execute()){
$rtn = "Success";
echo json_encode($rtn);
} else {
$rtn = "Failed";
echo json_encode($rtn);
}
$stmt->close();
$link->close();
}
However, in this example, an alert box appears empty. No errors in firebug or Apache logs.
Is it possible to: when I perform an submit using Ajax, I can recieve an echo "Text from error or success box"; which I can then put into a bootstrap alert?
The code I'm writing is new, so adapting to new libraries is something I would consider. This is purely for UI enhancement to show error or success messages, if the user has javascript disabled then the form default action wouldn't be prevented - they just wouldn't see a success or error message.
Something I have seen is "Javascript promises" I don't mind using Javascript if this is better in terms of useability, as I don't want to freeze the browser when a submit takes place.
Thanks for your time
Your code should look something like this
I would pass back a standard form of success/error from PHP. So failure might look like this:
json_encode(['success'=>false]);
Then acting on this in Javascript would look like this:
$.ajax({
url: "includes/contact-us.php",
type: "post",
data: $("#contact-form").serialize(),
success:function(data) {
data = JSON.parse(data);
if (data.success)
alert('success!');
else
alert('got failure response from PHP');
},
error:function(){
alert("failure");
}
});
You can use try catch() in php
<?php
// ...
try{
// your code
$msg = 'Success';
return json_encode($msg);
}catch(Exception $e){
$msg = 'Error';
return json_encode($msg);
}
?>
I'm making an app on phonegap.
I'm doing a script that read a ticket code (two queries, first to update the ticket status if exist on the db and second to write a log on another table). This is working fine.
But now, I want to get different responses (Valid or Invalid) with json, but I can't find a way to read the data and showing different responses.
Script on index.html
$(function() {
$("#savedata").click(function() {
var fcode = $("#code").val();
var fuuid = $("#uuid").val();
$("#code").val(" ");
$("#uuid").val(" ");
$.ajax({type: "POST",
url: "http://phonegap.localhost/test/www/db/update.php",
data: ({code: fcode, uuid: fuuid}),
cache: false,
dataType: "text",
success: Send
});
});
function Send(data){
document.getElementById('entrada').innerHTML = ("Done!");
}
});
Update.php
<?php
require_once('conndb.php');
$code= $_POST['code'];
$uuid = $_POST['uuid'];
$data=array();
$sql = "SELECT code FROM ticket WHERE code='$code'";
$result = mysql_query($sql);
if(mysql_num_rows($result) >0){
$sql="UPDATE ticket SET redeem_status= 1 WHERE code = '$code'";
$resultado=mysql_query($sql);
$sql2="INSERT INTO log (id, codigo, hora, uuid, valido) VALUES (NULL, '$code', CURRENT_TIMESTAMP, '$uuid', 1)";
$resultado2=mysql_query($sql2);
}
$val['status'] = 1;
echo json_encode($val);
}else{
$sql2="INSERT INTO log (id, codigo, hora, uuid, valido) VALUES (NULL, '$code', CURRENT_TIMESTAMP, '$uuid', 0)";
$resultado2=mysql_query($sql2);
$val['status'] = 0;
echo json_encode($val);
}
?>
In your javascript code you expect TEXT data but in php-script you sending json. So change dataType to json and fix function Send
Here is simple solution
$(function() {
$("#savedata").click(function() {
var fcode = $("#code").val();
var fuuid = $("#uuid").val();
$("#code").val(" ");
$("#uuid").val(" ");
$.ajax({type: "POST",
url: "http://phonegap.localhost/test/www/db/update.php",
data: ({code: fcode, uuid: fuuid}),
cache: false,
dataType: "json",
success: Send
});
});
function Send(data){
if (data.status == 0){
document.getElementById('entrada').innerHTML = ("Error!");
}
else{
document.getElementById('entrada').innerHTML = ("Done!");
}
}
});
You just have to create a new PHP page which is reading data in your DB and then returning it as JSON (as you're doing right now) and bind an action on a button for example with jQuery in your phonegap app to launch an Ajax call to this page then on success, you use a function to apply what you receive on the smartphone screen.
I'm trying to INSERT INTO a database using ajax. The table is updated by the php file, but I always get an error in ajax and the page could not be redirected to the results page.
My 'POST' function, in the html page is (it returns always the error alert):
function enviaFormDetalhes() {
if (confirm("Tem a certeza que quer gravar os dados?")){
$.ajax( {
type: 'post',
url: 'php/f_propostas.php?tipo_acao=grava_nova_proposta&id_consulta='+getUrlVars()['id_consulta']+'&id_fornecedor='+getUrlVars()['id_fornecedor'],
data: $("#form_detalhes_proposta").serialize(),
success: function(data) {
alert("Dados gravados com sucesso");
location.href = 'f_editproposal.html?id_proposta='+data;
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
} );
} else {
return false;
}
}
The part of php file is: (This is working good, if I call i directly in the browser it returns me the lastinsertID):
case "grava_nova_proposta":
$ID_Fornecedor = $_GET['id_fornecedor'];
$ID_Consulta = $_GET['id_consulta'];
$DataRececao = $_POST['dt_proposta'];
$RefProposta = $_POST['ref_proposta'];
$DtValidade = $_POST['dt_validade'];
$DtCriacao_loop = gmdate('Y-m-d');
try {
$sql = "INSERT INTO fornecedores_propostas (
id_fornecedor,
id_contacto,
id_consultaloop,
datarecepcao,
ref_proposta,
validadeproposta)
VALUES (?, ?, ?, ?, ?, ?)";
$q = $conn->prepare($sql);
$q->execute(array($ID_Fornecedor, $ID_Contacto, $ID_ConsultaLoop, $DataRececao, $RefProposta, $DtValidade));
$Ultimo_ID = $conn->lastInsertId('id_proposta');
echo $Ultimo_ID;
break;
try
url: 'php/f_propostas.php,
data: tipo_acao=grava_nova_proposta&id_consulta='+getUrlVars()['id_consulta']+'&id_fornecedor='+getUrlVars()['id_fornecedor']+$("#form_detalhes_proposta").serialize(),