How to return a ajax error? - php

I want to show a ajax error after submitting a form. It ends now with 'die'
but what is the best way to handle this? Just write something in this php file in 'script' tags?
if($_POST['postForm'] == 'newsletter'){
$newsletterSubscriber = new NewsletterSubscriber();
$newsletterSubscriber->set('CMS_newsletters_id', 2);
$newsletterSubscriber->set('created', date('Y-m-d H:i:s'));
$newsletterSubscriber->set('firstName', $_POST['voornaam']);
$newsletterSubscriber->set('lastName', $_POST['achternaam']);
$newsletterSubscriber->set('companyName', $_POST['beddrijfsnaam']);
$newsletterSubscriber->set('emailAddress', $_POST['email']);
$newsletterSubscriber->set('subscribed', 1);
$saved = $newsletterSubscriber->save();
die('subscriber added');
}
I tried several solutions I found but I can't get it to work.
Thanks!

All you need to do is create a array and place any parameters you want to pass back into that array, then use json_encode() to turn it into a json string that can be easily processed by javascript
if($_POST['postForm'] == 'newsletter'){
$newsletterSubscriber = new NewsletterSubscriber();
$newsletterSubscriber->set('CMS_newsletters_id', 2);
$newsletterSubscriber->set('created', date('Y-m-d H:i:s'));
$newsletterSubscriber->set('firstName', $_POST['voornaam']);
$newsletterSubscriber->set('lastName', $_POST['achternaam']);
$newsletterSubscriber->set('companyName', $_POST['beddrijfsnaam']);
$newsletterSubscriber->set('emailAddress', $_POST['email']);
$newsletterSubscriber->set('subscribed', 1);
$saved = $newsletterSubscriber->save();
$response = array('error_code'=>0,
'message'=>'subscriber added'
);
echo json_encode($response);
exit;
}
The javascript woudl be something like
$.ajax({
type: "POST",
url: "connection.php",
data: {param1: 'aaa'},
dataType: JSON
})
.done( function(data){
if(data.error_code == 0) {
alert(data.message);
}
});
Note when you use dataType:JSON the browser automatically converts the json string returned to a javascript object so you can address data.error_code and data.message in simple javascript object notation

You can do like:
if($saved) {
die('subscriber added');
} else {
echo "error";
}
and In ajax you can check:
$.ajax({
type: "POST",
url: "savedata.php",
data: form,
cache: false,
success: function(data){
if(data == "error") {
alert("Data has not been saved successfully. Please try again.");
window.location.reload(true);
}
}
});

Did you check jQuery Ajax API? this comes directly from their example.
It says that you can use the .done() .fail and .always() functions
var jqxhr = $.ajax( "example.php" )
.done(function() {
alert( "success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "complete" );
});

the best solution is to make you custom json and send it to ajax:
instead of die try:
$message = array('error'=>'subscriber added');
echo json_encode($message);
and in you ajax callback do:
function(success) {
if(success.error) {
//do stuff
}
//do stff
}

Use a json message followed by a error number:
if($saved) {
echo json_encode(array('message'=>'Successfully saved','erno'=>0));
} else {
echo json_encode(array('message'=>'Error on save','erno'=>1));
}
js:
success:function(data) {
if(data.erno == 1) {
alert(data.message)
//do other stuf here
} else {
alert(data.message)//if save was successful
}
}

Related

AJAX returns "success" function instead of "error" function

When I run this script, instead of the error inserting HTML in the page, it returns an alert like the success function - but with the error message instead.
AJAX
$(function() {
$('form').submit(function() {
$page_title = $('input[name="page_title"]').val();
$.ajax({
method: 'GET',
url: 'test-script.php',
datatype: 'jsonp',
jsonp: 'jsonp_callback',
data: {
page_title: ($page_title),
},
success: function(result){
alert(result);
},
error: function(result) {
$('#error').html('result');
}
});
});
});
PHP
<?php
if(isset($_GET)) {
if (! empty($_GET['page_title'])) {
$title = $_GET['page_title'];
print $title;
} else {
$error = ('Name required');
print $error;
}
}
add a http_response_code(); to your php to tell js, that there was an error. Also you better should send back a json encoded error string, that can be understood by javascript.
<?php
if(isset($_GET)) {
if (! empty($_GET['page_title'])) {
$title = $_GET['page_title'];
echo $title;
} else {
http_response_code(400);
$error = ["message"=>"Name required"];
echo json_encode($error);
}
}
See the list of appropriate response codes
EDIT:
Response to your comment "the HTML is inserted... then disappears"_:
You need to prevent the form from beeing submitted. To do that add event.preventDefault() to your onSubmit handler:
$('form').submit(function( event ) {
event.preventDefault();
// rest of your code...

how can i check if i got the value from my ajax to my controller

This is the event that will trigger the login
$('#btnLogin').click(function(){
//var data = $('#loginForm').serialize();
var email = $('#loginEmail').val();
var password = $('#loginPass').val();
var result = '';
if( email.trim() =='' ){
//username.addClass('alert-danger');
alert('email is required');
}else{
//username.removeClass('alert-danger');
result +='1';
}
if( password.trim()==''){
alert('password is required');
}else if(password.length < 8){
alert('password length must be atleast 8 characters');
}else{
//password.removeClass('alert-danger');
result +='2';
}
/*var postData = {
'email' : email,
'password' : password
};*/
if (result=='12') {
$.ajax({
type: "POST",
url: '<?php echo site_url('login/identifying_usertype'); ?>',
data: { email : email, password : password },
dataType: 'json',
success: function(response){
//console.log(response);
//alert(email);
$('#myModal').modal('hide');
},
error: function (XHR, status, error){
console.log('error', error);
}
});
}
});
This is my controller:
public function identifying_usertype()
{
if( $email = $this->input->post('email') )
{
echo json_encode( array('email' => $email) );
}
else
{
echo json_encode( array('error' => 'No email address') );
}
}
Now im getting {"error":"No email address"} on my console there's no error. Is there something I'm missing? on my ajax i added dataType: 'json', i changed the url from base_url to site url
Since you have success: function(response){, the return value of the Ajax is on the variable response and not on email. So doing this will fix your issue:
success: function(response){
email = response;
alert(email);
//$('#myModal').modal('hide');
},
1) The best way to create a link to one of your own controller/methods in CodeIgniter is to use site_url(), not base_url(). With site_url, your url becomes:
url: '<?php echo site_url('login/identifying_usertype'); ?>',
2) jQuery's $.ajax needs you to declare a dataType. Although if you leave it out jQuery will attempt to guess what it is, I've found it's wrong many times. Most people will use 'json':
dataType: 'json',
3) In your controller, if you are declaring that you want a json dataType, then it's really easy to send that back as the response:
echo json_encode( array('email' => $email) );
4) In your ajax success function, you can then do like this:
success: function( response ){
if( response.email ){
console.log(response.email);
}else{
console.log('email not verified');
}
}
5) Lastly, you are not showing code that would create an event to execute your ajax. If you need help with that, let me know and I'll show you.
6) All of the network traffic is available for you to view in your browser's console. Check it, as it is very helpful when creating these ajax requests.
Regarding your comment, how about this in the controller:
public function identifying_usertype()
{
if( $email = $this->input->post('email') )
{
echo json_encode( array('email' => $email) );
}
else
{
echo json_encode( array('error' => 'No email address') );
}
}

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

Validate if website exists with AJAX

I'm trying to check if a website exists with an ajax call, but I'm not sure I am getting it right. On my page I grab a URL on click
$("#go").click(function() {
var url = $("#url").val();
$.ajax({
type: "POST",
url: "/ajax.php",
data: "url="+url,
success: function(){
$("#start").remove();
},
error: function(){
alert("Bad URL");
}
});
});
a=And then check on ajax.php
$url = $_POST['url'];
ini_set("default_socket_timeout","05");
set_time_limit(5);
$f=fopen($url,"r");
$r=fread($f,1000);
fclose($f);
if(strlen($r)>1) {
return true;
} else {
return false;
}
It seems I am getting SUCCESS no matter what... What am I missing?
It seems I am getting SUCCESS no matter what... What am I missing?
This is extremely pretty straightforward.
Because of this reasons:
// You have no idea what server respond is.
// that is you can't parse that respond
success: function(){
$("#start").remove();
}
Which should be
success: function(respond){
//you don't have to return TRUE in your php
//you have to echo this one instead
if ( respond == '1'){
$("#start").remove();
} else {
//handle non-true if you need so
}
}
In php replace this:
if(strlen($r)>1) {
return true;
} else {
return false;
}
to
if(strlen($r)>1) {
print true; //by the way, TRUE is a constant and it equals to == 1 (not ===)
}
Oh yeah, also don't forget to fix this as well:
data: "url="+url,
to data : {"url" : url}
As Nemoden said, you get a success message even if it returns false.
You need to check the data returned and then remove the element.
for example
$("#go").click(function() {
var url = $("#url").val();
$.ajax({
type: "POST",
url: "/ajax.php",
data: "url="+url,
success: function(response){
if (response == 'whatever you are returning') {
$("#start").remove();
}
},
error: function(){
alert("Bad URL");
}
});
});
Success callback is called whenever server-side script returned an answer (there were no connectivity errors or server-side errors). Is this answering your question?
See the difference:
$("#go").click(function() {
var url = $("#url").val(),
ajax_data = {url: url};
$.post({
"/ajax.php?cb=?",
ajax_data,
function(response){
if (response.status) {
// URL exists
}
else {
// URL not exists
}
$("#start").remove();
},
'json'
});
});
php back-end:
printf('%s(%s)', $_GET['cb'], json_encode(array('status' => (bool)$url_exists)));

Find error PHP returns to AJAX in JQuery

this works:
$.ajax({
type: 'POST',
url: 'register.php',
data: {captcha: captcha
},
success: function() {
$('#loading').hide();
$('#success').fadeIn();
}
error: function() {
$('#loading').hide();
$('#captcha').fadeIn();
$('#catErrorB').fadeIn();
}
});
sends captcha response to PHP and if entered correctly, you can register. problem is, is that if you incorectly enter your captcha, the JQuery still runs the functions for a successful run although the PHP ran a "die" and did nothing.
In PHP, if the captcha is entered incorrectly is does this
if (!$resp->is_valid) {
die ("false");
}
else
{
register
}
How do I request the error that PHP spits out so I can do something like?
success: function(find error) {
if(error == "false")
{
$('#loading').hide();
$('#captcha').fadeIn();
$('#catErrorB').fadeIn();
}
else
{
$('#loading').hide();
$('#success').fadeIn();
}
}
EDIT!:
With your help heres what it looks like now and it works fantastic!!
$.ajax({
type: 'POST',
url: 'register.php',
dataType: "json",
data: {
challenge: challenge,
response: response,
zip: zip
},
success: function(result) {
if (!result.success) {
$('#loading').hide();
$('#captcha').fadeIn();
$('#catErrorB').fadeIn();
}
else {
$('#loading').hide();
$('#success').fadeIn();
}
}
});
and the PHP
if (!$resp->is_valid) {
$response = array(success => false);
echo json_encode($response);
}
else
{
$response = array(success => true);
echo json_encode($response);
Ya'll are the coolest. My first JQuery I've ever done, It's came out so awesome. This site rules!
I wouldn't use success/failure. Even if the script dies it is still going to return a 200 SUCCESS to your ajax call.
Use JSON to return responses depending on whether or not it is a success and parse and proceed with correct logic
<?php
if ( $resp->is_valid ) {
echo json_encode( array( 'status' => 'true' ) );
} else {
echo json_encode( array( 'status' => 'false' ) );
}
?>
Then you can parse the response in your AJAX call. Remember, if you call die('false'); that is still going to return a success message to your ajax function.
PHP:
if (!$resp->is_valid) {
$response = array(success => false);
echo json_encode($response);
}
else {
$response = array(success => true);
echo json_encode($response);
}
jQuery:
success: function(result) {
if (!result.success) {
// Wrong input submitted ..
}
else {
// Correct input submitted ..
}
}

Categories