Getting a different code outcome on different servers - php

This is updated based on an answer, but i still have a problem.
var dataString = $("#acc_form").serialize();
var action = $("#acc_form").attr('action');
$.ajax({
type: "POST",
dataType:"JSON",
url: action,
data: dataString,
success: function(res){
if(res.status === 'error'){
console.log('Error!!!');
} else{
console.log('Success!!!');
}
}
});
Here is where i do the check, and also where i am confused. my else statement looks wrong.
$desired_email = strip_tags(#$_POST['email']);
$email_exist_check = mysqli_query($connect, "SELECT * FROM accounts WHERE email='$desired_email'") or die(mysql_error());
$email_exist = mysqli_num_rows($email_exist_check);
if ($email_exist == 0) {
//performs insert query
} else {
header('Content-type: application/json');
$res['status'] = 'error';
echo json_encode($res);
}
Any help is greatly appreciated. I am new to jQuery and ajax and using json

Because you've returned a json array, even check email is invalid. You need to process the response data in success of ajax function. The error callback only works when server return status code on header (it isn't status in response data), i called it is Solution 1. In Solution 2, i solve it by return a header in PHP code.
Solution 1: Solve it on client (javascript)
//...
success: function(res){
// Use json parse method to parse the response data if it is string.
// If you have been to set dataType: 'json', it's ok. Can ignore this comment & code.
// res = JSON.parse(res);
status = res.status;
if(status == 'error'){
//Process the error in here
}
}
//...
Full ajax function example:
$.ajax({
url: 'index.php',
data: {email: 'vuong#gmail.com'},
method: 'POST',
dataType: 'json',
success: function(res){
if(res.status === 'error'){
console.log('Error!!!');
} else{
console.log('Success!!!');
}
}
});
It's work on my workplace!
Solution 2: Solve it on server (php)
// Add it to before `echo` line
header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
You only need to choose once in both. Good luck!
Sorry all because my English is not good.

Related

Get variable value from PHP in AJAX

I'm trying to catch a PHP variable in AJAX, but I'm not having much luck.
myCode.php
<?php
//myFunction that will return a status
if(myFunction() === true){
$status = "success";
}else{
$status = "failure";
}
?>
In my HTML, I have the following:
<script>
function initiate_delete() {
$.ajax({
url: '{$modulelink}&action=delete',
type: "post", //request type,
dataType: 'json',
data: {
type: 'test'
}
});
}
</script>
Is there any way to have AJAX wait for the PHP to execute and then get $status when I execute initiate_delete?
Thanks in advance.
Change code to
<?php
//myFunction that will return a status
if(myFunction() === true){
$status = "success";
}else{
$status = "failure";
}
echo $status
or short it to
echo myFunction() ? "success" : "failure";
To wait for an answer - you can execute the request asynchronously, and get the result in the .done() callback
$.ajax({
url: $(this).attr('href'),
type: 'POST',
fail: function(){
//do something
},
done: function(m){
/// do something else
}
});
Your PHP needs to return the value. If you want to keep the dataType Json (suggested) you just need to json_encode your output.
So the PHP becomes:
<?php
$type=$_POST['type'];
//myFunction that will return a status
if(myFunction() === true){
$status = "success";
}else{
$status = "failure";
}
echo json_encode('status'=>$status);
?>
Then you need to tell Ajax what to do with the answer received using .done()
So your Ajax will become:
$.ajax({
url: '{$modulelink}&action=delete',
type: "post", //request type,
dataType: 'json',
data: { type: 'test'}
}).done(function(data){
console.log(data.status);
});
Now you can do what you want with status but only in the .done() function. The rest of your js will be executed without waiting for ajax to return a value since it is asyncronous. So add here all the logic like dom manipulation and so on depending on this response.
Obviously you can have more data returned by php in the json and acccess them by key as done for status.

Not receive callback in success block of ajax submit options

I have an piece of code here, it's just an ajax options which I use to pass to my $(form).ajaxSubmit(submit_ajax_options)
var submit_ajax_options = {
url: init_param.server_url,
type: 'POST',
data: { agents_data : agents },
dataType: 'json',
timeout: 30000,
beforeSubmit: function( formData, jqForm, options ){
console.log('before submit');
form_loader.fadeIn();
},
success: function( response, status, xhr, $form ){
console.log('success callback');
form_loader.fadeOut();
if(response.status == 'ok'){
create_box('success', response.msg);
setTimeout(function(){
window.location.href = response.redirect;
}, 2000);
}
else{
create_box('danger', response.msg);
}
},
}
And this is my process code on my server (PHP):
<some processing code here>
$response['redirect'] = $redirect_url;
$response['status'] = 'ok';
$response['msg'] = "successfully";
//output data jsone
echo json_encode($response);
when I run as debug on my server, code ran ok without any mistake, but in my js code at client, I don't receive anything callback in my success block of submit_ajax_options (I don't see the logging string in my browser console, although the logging string in beforeSubmit block was printed)
I really have no any idea for this issue. Anybody can help me about my situation. really thank you a lots
You can try this if it helps you
$response['redirect'] = $redirect_url;
$response['status'] = 'ok';
$response['msg'] = "successfully";
//output data jsone
echo json_encode($response);
exit; // add exit so it stops execution and you can see the data in response
decode your JSON response
var data = JSON.parse(response);
console.log(data.status)

$.ajax call PHP include file return 500 error internal

here is it my code i call ajax by jquery $.ajax
js
$("#form-login").submit(function(){
var email = $("#menu_username");
$.ajax({
type: "post",
url: "register_cmd.php",
data: {email:email},
dataType: "json",
cache:false,
success:function(data){
if(data.c == "ok"){
window.location.reload();
} else {
alert(data);
}
return false;
}
})
});
register_cmd.php
<?PHP
include 'system/library/main.php';
$main = new mainQuery();
$chk_email = $main->checkEmail($email);
?>
main.php
function checkEmail($email){
$result = "function here";
return $result;
}
then it return 500 internal server error i don't know why
I just had this problem myself, even though i couldn't find the reason for it in my case, when changing from POST to GET, the problem 500 error disappeared!
because GET method sends the encoded user information appended to the page request.
type:'POST'
to
type:'GET'
I doing little changes in your codes. Just try this
var email = $("#menu_username").val(); // if you want to take the value from email field
$.ajax({
type: "POST",
url: "register_cmd.php",
data: {email:email},
dataType: "json",
cache:false,
success:function(data){
if(data.result == "ok"){
window.location.reload();
} else {
alert(data.result);
}
return false;
}
});
AND change the codes in register_cmd.php as follows
<?PHP
include 'system/library/main.php';
$main = new mainQuery();
$chk_email['result'] = $main->checkEmail($email);
print_r(json_encode($chk_email)); // if you are using json, you should use json_encode before it returns.
?>
the function in main.php need's a class arround it
class mainQuery {
public function checkEmail($email){
$result = "function here";
return $result;
}
}
otherwise you cannot instance new mainQUery;
also on top of everything to debug set
error_reporting(E_ALL);
ini_set('display_errors', true);
500 are serverside errors and have nothing to do with ajax.
probably this line:
var email = $("#menu_username");
might have to be
var email = $("#menu_username").text();
//or
var email = $("#menu_username").val();
It doesn't matter if it's a POST or GET request.

Jquery ajax POST response is null

I have a js script that does an ajax request and posts the data to a php script, this script with then echo something back depending if it works or not.
here is the JS
$(document).ready(function(){
var post_data = [];
$('.trade_window').load('signals.php?action=init');
setInterval(function(){
post_data = [ {market_number:1, name:$('.trade_window .market_name_1').text().trim()},
{market_number:2, name:$('.trade_window .market_name_2').text().trim()}];
$.ajax({
url: 'signals.php',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data:{markets:post_data},
dataType: "json",
success: function(response){
console.log("Response was " + response);
},
failure: function(result){
console.log("FAILED");
console.log(result);
}
});
}, 6000);
});
here is the php:
if(isset($_POST["json"]))
{
$json = json_decode($_POST["json"]);
if(!empty($json))
{
echo "IT WORKED!!!!";
}
else
echo "NOT POSTED";
}
So basically, i thought the response in the `success: function(response)' method would be populated with either "IT WORKED!!!" or "NOT POSTED" depending on the if statement in the php. Now everything seem to work because the js script manages to go into the success statement but prints this to the console:
Response was null
I need to be able to get the return from the server in order to update the screen.
Any ideas what I'm doing wrong?
Try:
if(isset($_POST["markets"]))
{
$json = json_decode($_POST["markets"]);
if(!empty($json))
{
echo "IT WORKED!!!!";
}
else
echo "NOT POSTED";
}
use this in your php file
if(isset($_POST["markets"]))
{
}
instead of
if(isset($_POST["json"]))
{
.
.
.
.
}
Obiously the if(isset($_POST["json"])) statement is not invoked, so neither of both echos is executed.
The fact that the function specified in .ajax success is invoked, only tells you that the http connection to the url was successful, it does not indicate successful processing of the data.
You are using "success:" wrong.
Try this instead.
$.post("signals.php", { markets: post_data }).done(function(data) {
/* This will return either "IT WORKED!!!!" or "NOT POSTED" */
alert("The response is: " + data);
});
Also have a look at the jQuery documentation.
http://api.jquery.com/jQuery.post/
Look, You send data in market variable not in json. Please change on single.php code by this.
$json_data = array();
if(isset($_POST["markets"]))
{
// $json = json_decode($_POST["markets"]);
$json = ($_POST["markets"]);
if(!empty($json))
echo "IT WORKED!!!!";
else
echo "NOT POSTED";
}
And change on your ajax function
$(document).ready(function(){
var post_data = [];
$('.trade_window').load('signals.php?action=init');
setInterval(function(){
post_data = [ {market_number:1, name:$('.trade_window .market_name_1').text().trim()},
{market_number:2, name:$('.trade_window .market_name_2').text().trim()}];
$.ajax({
url: 'signals.php',
type: 'post',
// contentType: 'application/json; charset=utf-8',
data:{markets:post_data},
dataType: "json",
success: function(response){
console.log("Response was " + response);
},
failure: function(result){
console.log("FAILED");
console.log(result);
}
});
},6000);
});
You have to you change you $.ajax call with
//below post_data array require quotes for keys like 'market_number' and update with your required data
post_data = [ {'market_number':1, 'name':'name1'},
{'market_number':2, 'name':'name2'}];
//console.log(post_data);
$.ajax({
url: "yourfile.php",
type:'post',
async: true,
data:{'markets':post_data},
dataType:'json',
success: function(data){
console.log(data);
},
});
and you php file will be
<?php
if(isset($_POST['markets']))
{
echo "It worked!!!";
}
else
{
echo "It doesn't worked!!!";
}
//if you want to work with json then below will help you
//$data = json_encode($_POST['markets']);
//print_r($data);
?>
in your php file check the $_POST:
echo(json_encode($_POST));
which will tell if your data has been posted or not and the data structure in $_POST.
I have used the following code to covert the posted data to associative array:
$post_data = json_decode(json_encode($_POST), true);

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