Ajax to submit form, and retrieve success/error - php

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);
}
?>

Related

Confirming A Database Row was deleted via PHP in aJax/jQuery

I'm trying to figure out the best way to relay back to ajax if the POST data sent to the .php file successfully deleted the data from the database. I'm not sure what to phrase what I'm looking for, but essentially I thought about a 'if() { } else { }' statement perhaps, but I'm not sure how to send the data back correctly into the success:function. Here is the basic code below that ajax is using. The PHP file is just standard code for running a deletion via php/mysqli.
$.ajax({
url: "../ajax/modules/delete-from-db.php",
data:{},
type:'POST',
success:function(data){
//IF() {
//EXECUTE SUCCESS & REMOVE DIV
//} ELSE {
//GIVE NOTICE OF DELETION FAILURE
//}
}
});
So anyone have any ideas how I could accomplish this?
On your php. depends on what you are using, you can check if the query was successful or not. then you can add anything on your return statement that you could use on your ajax success funtion.
Example:
on the php side using PDO
$success = true;
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$sql = "DELETE FROM MyGuests WHERE id=3";
$conn->exec($sql);
} catch (PDOException $e) {
$success = false;
}
return json_encode([
'success' => $success
])
Then on ajax. you can use this
$.ajax({
url: "../ajax/modules/delete-from-db.php",
data:{},
type:'POST',
success:function(data){
IF(data.success) {
//EXECUTE SUCCESS & REMOVE DIV
} ELSE {
//GIVE NOTICE OF DELETION FAILURE
}
}});
Some changes in your php file. if delete query return success then return true or 1 otherwise false or 0.
$.ajax({
url: "../ajax/modules/delete-from-db.php",
data:{},
type:'POST',
success:function(data){
if(data == 1){
alert("success");
} else {
alert("error");
}
}
});
it depends on what you send back from your php script, i recommend JSON which you could format as such
{
status:"success",//or error if failed
message:"record was successfully deleted"
}
in the php script you could have a Boolean flag to check if the record was deleted eg:
if($deleteFlag){
$response = array('status'=>'success', 'message'=>'record was successfully deleted');
} else {
$response = array('status'=>'error', 'message'=>'could not delete record!');
}
header('Content-type: application/json');
echo json_encode($response);

Ajax doesn't call server side function when jquery handler is fired

I'm building a simple forum on which I have a user details page with two text fields, one for the user's biography and another for his interests.
When the user clicks on the save icon, a handler on the jquery is suposed to call an ajax call to update the database with the new value of the biography/interests but the ajax call isn't being called at all and I can't figure it out since I don't find any problems with the code and would apreciate if someone could take a look at it.
this is the textarea:
<textarea rows="4" cols="50" id="biography" readonly><?php if($info['bio'] == "") echo "Não existe informação para mostrar";
else echo $info['bio']; ?></textarea>
Here is the icon the user clicks on:
<li style="display:inline;" class="infoOps-li"><img class="info-icons" id="save1" src="assets/icons/save.png" alt=""></li>
this is the jequery with the ajax call:
$("#save1").click(function(){
var bio = $("#biography").val();
alert(bio); //this fires up
$.ajax({
url:"assets/phpScripts/userBioInterest.php", //the page containing php script
type: "post", //request type,
dataType: 'json',
data: {functionName: "bio", info:bio},
success:function(result){
alert(result.abc); //this doesn't fire
}
});
$("#biography").prop("readonly","true");
});
I know that the jquery handler is being called correctly because the first alert is executed. The alert of the ajax success function isn't, so I assume that the ajax call isn't being processed.
On the php file I have this:
function updateBio($bio)
{
$user = $_SESSION['userId'];
$bd = new database("localhost","root","","ips-connected");
$connection = $bd->getConnection();
if($bio == "")
{
echo json_encode(array("abc"=>'empty'));
exit();
}
if($stmt = mysqli_prepare($connection,"UPDATE users SET biografia = ? WHERE user_id = ?"))
{
mysqli_stmt_bind_param($stmt,'si',$bio,$user);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
echo json_encode(array("abc"=>'successfuly updated'));
}
$bd->closeConnection();
}
if(isset($_POST['functionName']))
{
$function = $_POST['functionName'];
echo $function;
if(isset($_POST['info']))
$info = $_POST['info'];
if($function == "bio")
{
updateBio($info);
}
else if($function == "interest")
{
updateInterests($info);
}
}
Can anyone shed some light on why isn't the ajax call being called?
Thank you
EDIT: changed "function" to "functionName" in json data object as suggested.
A possible problem is dued to a wrong parsing of the PHP output (for example due to a PHP error). You are reading the output as JSON, so if the output is not a JSON, success callback will not be triggered.
$("#save1").click(function(){
var bio = $("#biography").val();
alert(bio); //this fires up
$.ajax({
url:"assets/phpScripts/userBioInterest.php",
type: "post", //request type,
dataType: 'json',
data: {function: "bio", info:bio},
success:function(result){
alert(result.abc); //this doesn't fire
},
error: function(result){
alert("An error has occurred, check the console!");
console.log(result);
},
});
$("#biography").prop("readonly","true");
});
Try with this code, and check if an error is printed to the console.
You can use complete too, check here: http://api.jquery.com/jquery.ajax/

Return success/failure variable with ajax from php script

I'm a really new coder and struggling with a task I'm now working on and trying out for days.
I searched Google and Stack Overflow but can't find a (for me understandable) solution to my problem:
I created a Twitter Bootstrap landing page and there a modal shows up when clicked. In this modal I have a form with a newsletter subscription:
<form id="newsletter" method="post">
<label for="email">Email:</label><br/>
<input type="text" name="email" id="email"/><br/>
<button type="submit" id="sub">Save</button>
</form>
<span id="result"></span>
Now I want to insert the data into a mySQL DB and do some basic validation that returns errors or a success message. The script works fine without ajax, but probably needs alterations on what it returns for ajax?
include("connection.php");
if ($_POST['email']) {
if(!empty($_POST['my_url'])) die('Have a nice day elsewhere.');
if (!$_POST['email']) {
$error.=" please enter your email address.";
} else if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$error.=" please enter a valid email address.";
}
if($error) {
$error= "There was an error in your signup,".$error;
} else {
$query="SELECT * FROM `email_list` WHERE email='".mysqli_real_escape_string($link, $_POST['email'])."'";
$result = mysqli_query($link, $query);
$results = mysqli_num_rows($result);
if ($results) {
$error.=" this email address is already registered.";
} else {
$query = "INSERT INTO `email_list` (`email`) VALUES('".mysqli_real_escape_string($link, $_POST['email'])."')";
mysqli_query($link, $query);
$message = "Thanks for subscribing!";
}
}
}
After a lot of reading ajax seems to be the way to do it without the bootstrap modal closing after submit (to suppress default event).
The insertion into the DB works fine, also the validation.
But I can't manage to get the different error messages displayed (stored in the $error variable of the php file) or alternatively the $message in case of success.
This is the jquery script:
$("#sub").submit(function (){
event.preventDefault();
$.ajax( {
url: "newsletter2.php",
type: "POST",
data: {email: $("#email").val()},
success: function(message) {
$("#result").html(message);
},
error: function(error) {
$("#result").html(error);
}
});
I try to display the value of the error and message variable in the php script within the #result span.
Any help is appreciated. Please formulate it very straight forward since I'm really new to this field.
Thank you a lot in advance.
Edit:
Added some to the php file to create an array and store the messages within:
$response = array();
$response['success'] = $success;
$response['error']= $errors;
exit(json_encode($response));
But have still some trouble to get the ajax to work. Tried the shorthand $.post instead of $.ajax but can't them now even to get to work posting data...
$("#sub").submit(function (){
event.preventDefault();
$.post("newsletter.php", {email: $("#email").val() });
});
Quick time is much appreciated. I'm stuck after hours of testing and can't find the error. If I submit the form regularly it works fine, so the php/mysql part isn't the problem.
I also realized that when I click the "#sub" button, it still tries to submit the form via get (URL gets values passed). So I'm not sure if the event.preventDefault(); isn't working? jQuery is installed and working.
The $.ajax error function gets called when there is a connection error or the requested page cannot be found
You have to print some text out with the php and the ajax success function gets this output. Then you parse this output to see how it went.
The best practice is this:
php part:
$response = array();
$response['success'] = $success;
$response['general_message'] = $message;
$response['errors'] = $errors;
exit(json_encode($response));
js/html part:
$.post("yourpage.php", a , function (data) {
response = JSON.parse(data);
if(response['success']){
//handle success here
}else{
//handle errors here with response["errors"] as error messages
}
});
Good luck with your project
You need to echo your messages back to your AJAX. There is no place in you PHP code where the messages are going back to the message variable in your AJAX success.
include("connection.php");
if ($_POST['email']) {
if(!empty($_POST['my_url'])) die('Have a nice day elsewhere.');
if (!$_POST['email']) {
$error.=" please enter your email address.";
echo $error; die;
} else if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$error.=" please enter a valid email address.";
echo $error; die;
}
if($error) {
$error= "There was an error in your signup,".$error;
echo $error; die;
} else {
$query="SELECT * FROM `email_list` WHERE email='".mysqli_real_escape_string($link, $_POST['email'])."'";
$result = mysqli_query($link, $query);
$results = mysqli_num_rows($result);
if ($results) {
$error.=" this email address is already registered.";
echo $error; die;
} else {
$query = "INSERT INTO `email_list` (`email`) VALUES('".mysqli_real_escape_string($link, $_POST['email'])."')";
mysqli_query($link, $query);
$message = "Thanks for subscribing!";
echo $message; die;
}
}
}
I basicly just had the same case. I structured my code a little bit different but it works so...
$("#sub").submit(function (){
event.preventDefault();
$.ajax( {
url: "newsletter2.php",
type: "POST",
dataType: 'json',
data: {email: $("#email").val()},
})
.success(function(message) {
$("#result").html(message);
}),
.error(function(error) {
$("#result").html(error);
})
on server side I used C#(asp.net) and just returned a Json
return Json(new { Message = "Something...", Passed = true}, JsonRequestBehavior.AllowGet);
Oukay, finally I managed to solve the problem with the great inputs here. I did the following:
PHP:
$response = array();
$response['success'] = $success;
$response['error'] = $error;
exit(json_encode($response));
JS:
$("#newsletter").submit(function(event) {
event.preventDefault();
$.ajax({
url: 'newsletter3.php',
method: 'post',
data: {email: $('#email').val()},
success: function(data) {
var response = JSON.parse(data);
console.log(response);
if (response['success']) {
$("#error").hide();
$("#success").html(response['success']);
$("#success").toggleClass("alert alert-success");
} else {
$("#error").html(response['error']);
if(!$("#error").hasClass("alert alert-danger"))
$("#error").toggleClass("alert alert-danger");
}
}
});
});
The functionality is now that you click on a button and a modal pops-up, then you can enter your email and the php script validates if its valid and if it's already in the db. Error and success messages get JSON encoded and then are displayed in a span that changes color according to bootstrap classes danger or success.
Thank you very much for helping me, I'm very happy with my first coding problem solved :)
I use this on my ajax
request.done(function (response, data) {
$('#add--response').html(response);
});
and this on the PHP
die("Success! Whatever text you want here");

Form Validation With Record Saved Message

I wonder whether someone may be able to help me please.
Firstly, my apologies, I'm relatively new to JavaScript and jQuery, so perhaps this is a really stupid question.
Using these tutorials here and here I've put together this page to allow users to add records to a MySQL database but I'm having a little difficulty with the form 'validation' and jQuery 'submission' message.
If use select the above link, then once the page has loaded, select 'Save', you'll see that the correct field validation is activated, but despite being validation errors, the 'Location saved' message appears at the bottom of the page, and the page refreshes saving the record to the database.
Obviously this is not supposed to happen, but I'm having great difficulty in joining the 'validation' and 'submission' message. Independently they work fine, but as you can see, once together they don't.
The code below deals with the 'Save Record' and refresh of the page
UPDATE - Working Solution Below
<script>
jQuery(document).ready(function(){
jQuery("#addlocation").validationEngine();
$("#addlocation").bind("jqv.field.result", function(event, field, errorFound, prompText){ console.log(errorFound) })
});
</script>
<script type="text/javascript">
$(document).ready(function(){
$('#addlocation').submit(function(){
//check the form is not currently submitting
if($(this).data('formstatus') !== 'submitting'){
//setup variables
var form = $(this),
formData = form.serialize(),
formUrl = form.attr('action'),
formMethod = form.attr('method'),
responseMsg = $('#saverecordresponse');
//add status data to form
form.data('formstatus','submitting');
//show response message - waiting
responseMsg.hide()
.addClass('response-waiting')
.text('Please Wait...')
.fadeIn(200);
//send data to server for validation
$.ajax({
url: formUrl,
type: formMethod,
data: formData,
success:function(data){
//setup variables
var responseData = jQuery.parseJSON(data),
klass = '';
//response conditional
switch(responseData.status){
case 'error':
klass = 'response-error';
break;
case 'success':
klass = 'response-success';
break;
}
//show reponse message
responseMsg.fadeOut(200,function(){
$(this).removeClass('response-waiting')
.addClass(klass)
.text(responseData.message)
.fadeIn(200,function(){
//set timeout to hide response message
setTimeout(function(){
responseMsg.fadeOut(200,function(){
$(this).removeClass(klass);
form.data('formstatus','idle');
});
},3000)
});
});
}
});
}
//prevent form from submitting
return false;
});
});
</script>
and this is the 'saverecord.php' script which is called upon selecting the 'Save' button.
<?php
//sanitize data
$userid = mysql_real_escape_string($_POST['userid']);
$locationname = mysql_real_escape_string($_POST['locationname']);
$returnedaddress = mysql_real_escape_string($_POST['returnedaddress']);
//validate email address - check if input was empty
if(empty($locationname)){
$status = "error";
$message = "You didn't enter a name for this location!";
}
else if(!preg_match('/^$|^[A-Za-z0-9 _.,]{5,35}$/', $locationname)){ //validate email address - check if is a valid email address
$status = "error";
$message = "You have entered an invalid Location Name!";
}
else{
$query = mysql_query("INSERT INTO `table` (userid, locationname, returnedaddress) VALUES ('$userid', '$locationname', '$returnedaddress')");
if($query){ //if insert is successful
$status = "success";
$message = "Location Saved!";
}
else { //if insert fails
$status = "error";
$message = "I'm sorry, there has been a technical error! Please try again. If problems persist please contact Map My Finds support.";
}
}
//return json response
$data = array(
'status' => $status,
'message' => $message
);
echo json_encode($data);
exit;
?>
I just wondered whether someone could possibly take a look at this please and let me know where I'm going wrong.
Many thanks and kind regards
I believe you need:
if($.validationEngine.submitForm(this,settings) == true) {return false;}
somewhere before your $.ajax line
IRHM, check that the form is validate before submit in your event i.e.
$('#addlocation').submit(function(){
if($(this).validate()){
// put your all existing content here.
}
});
To prevent submitting the form after ajax put return false at the end of above script in if block i.e.
if($(this).validate()){
// put your all existing content here.
return false;
}
I guess the problem is occurring due to validation engine, so in that case to prevent form to submit try to use as follows:
$('#addlocation').submit(function(evt){
if($(this).validate()){
evt.preventDefault();
// put your all existing content here.
}
});
If the above code doesn't work then include onValidationComplete event with validationEngine and put you all existing stuff of if($(this).validate()) block in that i.e.
jQuery(document).ready(function(){
// binds form submission and fields to the validation engine
jQuery("#addlocation").validationEngine({ onValidationComplete: function(){
//setup variables
//add status data to form
//show response message - waiting
//send data to server for validation
return false;
}
});
});
Good Luck
After several days of working on this, I now have a working solution by using the example here which I've added to my original post.

Pass data from JQuery to database via Javascript/AJAX/JSON/PHP

I am attempting to add data to my database from my HTML code via the use of JQuery, AJAX/JSON and PHP using an MVC model. Below is a small sample of what I am looking to achieve.
In my front end I have a checkbox with different options and a button named 'Add'. The selected elements from here are picked up by a Javascript function, which I have tested properly, once this is done I call another Javascript function to do the AJAX/JSON . What I am still fresh on is the actual AJAX/JSON process that sends the data to PHP.
My Javascript function:
function add_fruits(fruit_name, fruit_type){
var success = "Fruit added";
var error = "Fruit not added";
var params = {
'fruit_name' : fruit_name,
'fruit_type' : fruit_type
};
$.ajax({
type: "POST",
url: "add_fruits.php",
async: false,
data: params,
success: function(success){
alert(success);
},
error: function(error){
alert(error);
}
});
}
My PHP function:
<?php
header("Access-Control-Allow-Origin: *");
header('Content-type: application/json');
require_once 'lib/connection_files.php';
if($_SERVER['REQUEST_METHOD'] =='POST')
{
$fruit_name = no_sql_injection($_POST['fruit_name']);
$fruit_type = no_sql_injection($_POST['fruit_type']);
$fruits = new fruits();
$result = $fruits->add_fruits($fruit_name, $fruit_type);
$tmp = mysql_num_rows($result);
if($result == 1)
{//RESULT must return 1 to verify successful insertion to database
//send confirmation to front end
}
else
{
//send error message to front end
}
}
else{
//tell front end there was error sending data via AJAX
}
?>
Note that the add_fruits() function takes care of doing the Queries to the database, I did not include it here because it is irrelevant to my issue.
Just do echo in your PHP:
PHP
else {
//send error message to front end
echo "Error Adding Fruits";
}
JS
success: function(data) {
if (data == "1") {
//data added to db
}
else {
alert(data);
}
}

Categories