Returning php variable from jQuery ajax call - php

Im sure this is a simple solution, however I have had no success in my attempts as my jQuery & ajax is not the greatest. I am making an ajax call to my php script which is doing error checking for a form. If there are errors, I am showing a hidden div and displaying the error messages no problem. However if there are no error messages, I would like an alert to appear. The issue is the alert does not display when there are no errors
Javacript
$.ajax({
url: '../assets/inc/process.php',
type: 'post',
data: formData,
dataType: 'html'
})
.always(function(data){
if (data == 'success'){
alert('it worked!');
}
else{
$('#responsediv').show();
$('#responsediv').html(data);
}
});
});
I have also tried
if (data.success == 'success'){
alert('it worked!');
}
else{
$('#responsediv').show();
$('#responsediv').html(data);
}
PHP
if ($result_new_row){
$success = 'success';
echo $success;
}
I know for sure that the new row is being inserted as I can see it in the database.
Any help is appreciated. Thanks!

Pass the data back from PHP as an array (PS data type should be json)
PHP
if ($result_new_row){
$return['result'] = 'success';
//comment this out when you are positive it's working
echo "hello";
} else {
$return['result'] = 'error';
}
print(json_encode( $return);
jQuery
$.ajax({
url: '../assets/inc/process.php',
type: 'post',
data: formData,
dataType: 'json'
})
.always(function(data){
if (data.result == 'success'){
alert('it worked!');
} else {
$('#responsediv').show();
$('#responsediv').html(data);
}
});
});
If this isn't returning correctly make sure your PHP function is actually working right first.
If you use Chrome you can see your AJAX calls by bringing up the inspector and changing to the network tab, then clicking XHR will show you each AJAX request, what is being sent and the response.

Related

Ajax call returning current page full page HTML instead of the expected data

I am trying to make an Ajax call but the result is my current page full HTML code. I have removed all the codes inside the php file except for that one line (below) but the error still persists, Please i need help here. which part of the ajax call is calling the current page html?Here is my PHP code,
<?php
echo "success";
?>
Ajax call
//TRANSFER MODULE AJAX CALL
$(document).ready(function(){
$('#transfer_Form').submit(function(){
let datatopost = $(this).serializeArray();
$.ajax({
url: 'transfer.php',
data: datatopost,
cache: false,
type: 'POST',
success: function(result){
if(result == 'success'){
$('#transfer_msg'). html(result);
}else{
$('#transfer_msg'). html('Nothing come out');
}
},
error: function(){
$('#transfer_msg'). html("Error transfer");
}
});
return false;
});

AJAX call not returning values from PHP

I am making an AJAX call but its not returning a value in the success handler. This is my AJAX call. I have checked that it's hitting the PHP file correctly
var msj;
$.ajax({
type: "POST",
url: "ajaxFile.php",
data: {
name: name,
status: status,
description: description,
action: 1
},
sucess: function(data){
msj = data;
alert(data);
}
});
alert(msj);
My PHP code is as follow:
if (isset($_POST['action']))
{
if ($_POST['action'] == 1)
{
$obj = new project($_POST['name'], $_POST['active'], $_POST['description']);
$obj = testInput($obj);
$check = validateName($obj->getName());
if ($check == 1)
{
echo $nameError;
}
else
{
print "asdasdasd";
}
}
}
Please help me tracking the mistake.
As far as I can see there's a syntax error in your code. There's sucess instead of success.
You are only providing a "success" callback function. You should also provide an "error" callback so you can debug and see what is wrong. You can also provide a "complete" callback that will be used in both alternatives.
var msj;
$.ajax({
type:"POST",
url:"ajaxFile.php",
data:{name:name,status:status,description:description,action:1},
complete:function(data){
msj=data;
alert(data);
}
});
alert(msj);
In your PHP, you could add
header('Content-Type: application/json');
to make sure JQuery identify well your web service.

Identifying what is returned when submitting a form using jquery

Is it possible to identify what a page returns when using jquery? I'm submitting a form here using jquery like this:
$("#sform").submit(function() {
$.ajax({
type: "POST",
data: $(this).serialize(),
cache: false,
url: "user_verify.php",
success: function(data) {
$("#form_msg").html(data);
}
});
return false;
});
​
The user_verify.php page does its usual verification work, and returns error messages or on success adds a user to the db. If its errors its a bunch of error messages or on success its usually "You have successfully signed up". Can I somehow identify using jquery if its errors messages its returning or the success message. So that way if its errors I can use that data in the form, or if its success, I could close the form and display a success message.
Yes, it's this:
success: function(data) {
$("#form_msg").html(data);
}
You can manipulate data in any way you want. You can return a JSON (use dataType) encoded string from server side and process data in the success function
success: function(data) {
if(data->success == 'ok'){
// hide the form, show another hidden div.
}
}
so user_verify.php should print for example:
// .... queries
$dataReturn = array();
$dataReturn['success'] = 'ok';
$dataReturn['additional'] = 'test';
echo json_encode($dataReturn);
die; // to prevent any other prints.
You can make you php return 0 if error so you do something like this inside
success: function(data) {
if(data==0){
//do error procedure
}else{
//do success procedure
}
}
Hope this helps
You can do and something like this:
$.ajax({
type:"POST", //php method
url:'process.php',//where to send data...
cache:'false',//IE FIX
data: data, //what will data contain
//check is data sent successfuly to process.php
//success:function(response){
//alert(response)
//}
success: function(){ //on success do something...
$('.success').delay(2000).fadeIn(1000);
//alert('THX for your mail!');
} //end sucess
}).error(function(){ //if sucess FAILS!! put .error After $.ajax. EXAMPLE :$.ajax({}).error(function(){};
alert('An error occured!!');
$('.thx').hide();
});
//return false prevent Redirection
return false;
});
You can checke the "data" parameter in "success" callback function.
I noticed that there is a problem in your code. Look at this line :
data: $(this).serialize(),
Inside $.ajax jquery method, "this" is bind to the global window object and not $('#sform')

return php variable to jquery ajax

I have an ajax function in jquery calling a php file to perform some operation on my database, but the result may vary. I want to output a different message whether it succeeded or not
i have this :
echo '<button id="remove_dir" onclick="removed('.$dir_id.')">remove directory</button>';
<script type="text/javascript">
function removed(did){
$.ajax({
type: "POST",
url: "rmdir.php",
data: {dir_id: did},
success: function(rmd){
if(rmd==0)
alert("deleted");
else
alert("not empty");
window.location.reload(true);
}
});
}
</script>
and this
<?php
require('bdd_connect.php');
require('functions/file_operation.php');
if(isset($_POST['dir_id'])){
$rmd=remove_dir($_POST['dir_id'],$bdd);
}
?>
my question is, how to return $rmd so in the $.ajax, i can alert the correct message ?
thank you for your answers
PHP
<?php
require('bdd_connect.php');
require('functions/file_operation.php');
if (isset($_POST['dir_id'])){
$rmd=remove_dir($dir_id,$bdd);
echo $rmd;
}
?>
JS
function removed(did){
$.ajax({
type: "POST",
url: "rmdir.php",
data: {dir_id: did}
}).done(function(rmd) {
if (rmd===0) {
alert("deleted");
}else{
alert("not empty");
window.location.reload(true);
}
});
}
i advice to use json or :
if(isset($_POST['dir_id'])){
$rmd=remove_dir($dir_id,$bdd);
echo $rmd;
}
You need your php file to send something back, then you need the ajax call on the original page to behave based on the response.
php:
if(isset($_POST['dir_id'])){
$rmd=remove_dir($dir_id,$bdd);
echo "{'rmd':$rmd}";
}
which will output one of two things: {"rmd": 0} or {"rmd": 1}
We can simulate this return on jsBin
Then use jquery to get the value and do something based on the response in our callback:
$.ajax({
type: "POST",
dataType: 'json',
url: "http://jsbin.com/iwokag/3",
success: function(data){
alert('rmd = ' + data.rmd)
}
});
View the code, then watch it run.
Only I didn't send any data here, my example page always returns the same response.
Just try echoing $rmd in your ajax file, and then watching the console (try console.log(rmd) in your ajax response block)
$.ajax({
type: "POST",
url: "rmdir.php",
data: {dir_id: did},
success: function(rmd){
console.log(rmd);
}
});
You can then act accordingly based on the response
Try echo the $rmd out in the php code, as an return to the ajax.
if(isset($_POST['dir_id'])){
$rmd=remove_dir($dir_id,$bdd);
//if $rmd = 1 alert('directory not empty');
//if $rmd = 0 alert('directory deleted');
echo $rmd;
}
Your "rmd" in success: function(rmd) should receive the callabck.

jQuery, AJAX - How to tell if script returned false

I'm using jQuery and AJAX to validate my form when someone creates a new user on my website. I'm programming in OOP PHP, together with the jQuery and AJAX.
I'm using this code:
$.ajax({
type: "POST",
url: "includes/classes/handler.php?do=addLogin",
data: dataString,
success: function() {
$('.sideBarNewUserWrap').fadeOut();
}
});
return false;
But how do I return an error message, if the e-mail already exists?
Hope it's info enough, else I'll just add some more.
Thanks in forward :)
* UPDATE *
This is my PHP checking if email exists:
$email_count = mysql_num_rows($check_email);
if($email_count){
return false;
}
* UPDATE *
success: function(data){
if(data.error){
$('.sideBarNewUserWrap').fadeOut();
} else {
$('.sideBarNewUserError-email').fadeIn();
}
Now this looks pretty much as a failure because.
if(data.error) then it's okay?
Shouldn't it be something like:
if(date.error){
//Error message
}
And not the other way around?
Well, If I try to enter an email which already exists, it tells me as it should, but why does this work? In my eyes I'm doing something wrong here?
php:
$result = array('error' => true); // or $result = array('error' => false);
echo json_encode($result);
js:
success: function(response) {
if (response.error) {
// ...
}
}
You can get the response in the function:
$.ajax({
type: "POST",
url: "includes/classes/handler.php?do=addLogin",
data: dataString,
success: function(response) {
if (response == "ok")
{
$('.sideBarNewUserWrap').fadeOut();
}
else
{
// error happend
}
}
});
return false;
You can return string, int in PHP or even XML, JSON, whatever you want to validate on client side
You can return data by using an echo in your handler.php file.
To receive this in jQuery just place a parameter in the success function of the Ajax function.
success: function(returnedValue)
{
// Here you check if returned value e.g. "returnedValue == 1"
}
basically in the handler.php you should verify whether email already exists or not and then send to the client (at least) two different responses (eg. 0: email exists, 1:ok).
In the success callback you can read the response data so you can tell the user the operation status

Categories