Jquery/php output custom error messagge - javascript

I have an Ajax autocomplete box on an input field of a form. In jquery, I have the following ajax settings
$.ajax({
type: "POST",
url: myUrl,
data: $("#id__form").serialize(),
success: function(data){
alert("do something");
},
error: function (xhr, textStatus, thrownError) {
alert(xhr.status+ " "+ thrownError+ " " + textStatus);
},
dataType: "json"
});
On the server side, I have this php code
$data = array('type' => 'error', 'message' => 'Error: '.$text);
header('HTTP/1.1 400 Bad Request');
header('Content-Type: application/json; charset=UTF-8');
die(json_encode($data));
All works fine both in case of success and in case of error. However, I didn't figure out how do I access from jquery the text I defined in php as $text
xhr.status is 400, textStatus is "error" and thrownError is "Bad Request", but no signs of what I defined as $text
What I am missing?

if you echo the $text variable in your file you can get to it from your javascript file.
php code:
echo $text;
change to javascript:
$.ajax({
type: "POST",
url: myUrl,
data: $("#id__form").serialize(),
success: function(data){
//do something with the data returned from php file
alert(data);//<---change to javascript code
},
error: function (xhr, textStatus, thrownError) {
alert(xhr.status+ " "+ thrownError+ " " + textStatus);
},
dataType: "json"
});

In your ajax post you defined a json call. In your php backend you defined a array, so you can access these params by key. Your array:
<?php
$arr = array();
$arr['message'] = 'What you like?';
$arr['errorCode'] = '12345';
die(json_encode($arr));
?>
In your case you will have access the data argument by adding the key, like data.message:
success: function(data){ alert(data.message); }
So, it have to look like that:
$.ajax({
type: "POST",
url: myUrl,
data: $("#id__form").serialize(),
success: function(data){
alert(data.message+' '+data.errorCode);
$('#someDivTag').html(data.message);
},
dataType: "json"
});

Got it, thanks to this article http://wingkaiwan.com/2012/10/21/deserialize-error-in-json-for-jquery-ajax/
The problem was that the variable data in the success callback handles automatically json, but I had to parse it in the error callback. This works:
error: function (xhr, ajaxOptions, thrownError) {
var error = JSON.parse(xhr.responseText);
alert(error.message);
}

Related

How can i send data attribute from html with ajax to some.php page, on click?

In this case, i'm getting product id from database and placing it into data-idproduct:
<a class="cart" href="" data-idproduct="<?php echo $itemArtikal['id_product'] ?>">Add to Cart</a>
Clicking on that "Add to cart" button i'm getting that stored data-idproduct and trying to send it to cart-process.php page.
Here is my main.js code:
$(document).ready(function (){
$('.cart').click(function (e) {
e.preventDefault();
let dataIdArtikla = $(this).data('idproduct');
$.ajax({
method: "post",
url: "models/cart-process.php",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({
"idProd" : dataIdArtikla
}),
success: function (response) {
alert(response);
},
error: function (xhr, textStatus) {
alert("oh no: "+ " " + xhr.status+ " " +textStatus.responseText);
}
})
});
})
And here is the basic cart-process.php code:
$idProduct = $_POST['idProd'];
header('Content-type: application/json');
echo json_encode([
'id_product' => $idProduct
]);
It always returns the error and the response of JSON is always null
Response from 'Network' tab:
<br />
<b>Warning</b>: Undefined array key "idProd" in <b>C:\xampp\htdocs\freshshop01\models\cart-process.php</b> on line <b>5</b><br />
{"id_artika":null}
Generally the idea behind this is adding the products into the cart when user click "Add to cart" button. I'm trying to pass the id of clicked product and after that in cart-process.php display whole product info with the same id.
I have no idea how to fix it, can anyone help?
Edit:
Here is my new cart-process.php file:
<?php
$idArtikla = $_POST['idProd'];
if(isset($idArtikla)) {
require_once "../config/connection.php";
session_start();
$_SESSION['idArtikla'] = $idArtikla;
$queryCart = $conn -> prepare('SELECT * FROM artikal WHERE id_artikal = :idArtikal');
$queryCart->bindParam(":idArtikal", $idArtikla);
try {
$queryCart->execute();
$resultCart = $queryCart->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $exception) {
echo json_encode(['error' => $exception->getMessage()]);
}
header('Content-type: application/json');
echo json_encode($resultCart);
}
And new main.js file:
$(document).ready(function (){
$('.cart').click(function (e) {
e.preventDefault();
let dataIdArtikla = $(this).data('idartikla');
$.ajax({
method: "post",
url: "models/cart-process.php",
dataType: 'json',
data: {
"idProd" : dataIdArtikla
},
success: function (response) {
console.log("Success message: " + response);
},
error: function (xhr, textStatus) {
alert("oh no: "+ " " + xhr.status+ " " +textStatus.responseText);
}
})
});
})
Response now returns whole object, but it wont proceed to success. It enters error. I suspect there is something wrong with object to json conversion or vice versa, but not sure what exactly could be wrong here?
Here is how response and request look like exactly:
Post is a little bit to long, i appriciate the help.
When passing data you have to add a key to your JSON.
Instead of the contentType use dataType:'json' to tell jQuery what to expect.
$.ajax({
method: "post",
url: "models/cart-process.php",
dataType: 'json',
data: {'json':JSON.stringify({"idProd" : dataIdArtikla})},
success: function (response) {
alert(response);
},
error: function (xhr, textStatus) {
alert("oh no: "+ " " + xhr.status+ " " +textStatus.responseText);
}
})
And in the php you can access the element like so:
echo (json_decode($_POST['json'])->idProd);
A simpler way would be to just pass the data without serialization
$.ajax({
method: "post",
url: "models/cart-process.php",
data: {"idProd" : dataIdArtikla},
success: function (response) {
alert(response);
},
error: function (xhr, textStatus) {
alert("oh no: "+ " " + xhr.status+ " " +textStatus.responseText);
}
})
Then you can access the idProd directly via $_POST:
echo ($_POST['idProd']);

Send multiple parameters to PHP (Ajax)

I'm stuck here when passing or sending multiple parameters on Ajax. It only works when I pass one. Here the Ajax code:
$.ajax({
type: "POST",
url: "dataCartas.php",
data: {valorXY: valorXY,
CentroX: CentroX},
success: function(msg){
// return value stored in msg variable
console.log(valorXY + CentroX)
}
});
And the PHP code:
$valorXY = $_POST['valorXY'];
$CentroX = $_POST['CentroX'];
include "configX.php";
if ($conn){
$sql="EXEC sp_InsertaComID #ComID = '".$valorXY."', #DR =
'".$CentroX."'";
if ($rs=sqlsrv_query($conn,$sql)){
}else{
echo (print_r(sqlsrv_errors(), true));
}
}else{
die(print_r(sqlsrv_errors(), true));
}
Sorry for my bad english :(
You can serialize a form
$.ajax({
type: 'post',
url: 'include/ajax.php',
data: $('#form').serialize(),
success: function (response) {
// do something
},
error: function(jqxhr,textStatus,errorThrown){
console.log(jqxhr);
console.log(textStatus);
console.log(errorThrown);
}
});
you can also use form data https://stackoverflow.com/a/8244082/3063429

data is empty from ajax request in whcms

I am trying to send a post request using ajax in whcms, but it seems that the data from the ajax request is null.
This is the ajax request:
function send_request(ticket_or_credit){
if(ticket_or_credit == 'ticket'){
var url = $("#ticket_action").val();
var ticket = $("#ticket_ticket").val();
var solution = $("#ticket_solution").val();
whmcs_data={ request_type:ticket, solution:solution };
jQuery.ajax({
type: 'POST',
url: url,
data: JSON.stringify(whmcs_data),
contentType:"application/json; charset=utf-8",
dataType: 'json',
success: function(results){
console.log(results);
console.log(whmcs_data);
},
error( xhr, ajaxOptions, thrownError ){
console.log( thrownError );
}
});
}
}
and in my php file:
$json = array("result" => "success", "message" => "Method is post", "data" => $_POST);
echo json_encode($json);
The $_POST is null.
Please help me, I haven't solve this problem for how many days :(
I removed the contentType and dataType of the ajax code just to make it default application/x-www-form-urlencoded; charset=UTF-8') and properly serialized whmcs_data variable. The output of your JSON.stringify is not properly serialized so I manually serialized it. for more information on ajax go to this : http://api.jquery.com/jquery.ajax/ and for JSON.stringify - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
try to replace variable whmcs_data declaration and ajax code with this:
whmcs_data = {
"request_type": ticket,
"solution": solution
};
$.ajax({
type: 'POST',
url: url,
data: whmcs_data,
success: function(results){
console.log(results);
console.log(whmcs_data);
},
error( xhr, ajaxOptions, thrownError ){
console.log( thrownError );
}
});

Handle data from ajax request after call

I'm using ajax to get the returned value from php function, the call is correct but I can't access the data properly.
The ajax call is:
$.ajax({
data: {"hotel_id" : hotel_id},
url: '/get_type_check',
type: 'get',
success: function (response) {
console.log(response);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
});
If I print the console log shows:
<!DOCTYPE html>
comment:
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
{"status":["CAB2"]}
And the php function:
public function get_type_check(){
$type_checks=Hotel::get_type_checks($_GET['hotel_id']);
echo json_encode(array('status' => $type_checks));
}
How can I get the response.status?
Should I use return instead of "echo"?
You have to parse the response to json to catch it as json.
Just add the line:
var data = $.parseJSON(response);
So your ajax will as follows:
$.ajax({
data: {"hotel_id": hotel_id},
url: 'ajax.php',
type: 'get',
success: function(response) {
var data = $.parseJSON(response);
console.log(data.status);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus);
alert("Error: " + errorThrown);
}
});
});

Unexpected character error in JQuery ajax function

I have the 'unexpected character error' problem, my Jquery ajax code looks like that:
function test(){
if(true){
$.ajax({
type: 'POST',
url: 'test.php',
dataType: 'json',
data: {
godot: 'godot',
jobadze: 'jobadze'
},
success: function(data){
alert(data);
},
error: function(jqXHR, textStatus, errorThrown) { alert("Error Status: "+textStatus+"\nMessage: "+errorThrown);
}
});
and this is the php code:
<?php
echo 'test';
?>
it should alert "test", but it calls error. What is going on?
You're not returning any JSON. You returning text but you've specified in the AJAX that it will return json.
You have: dataType: 'json',
You could change the dataType: 'text', if you will always be returning text
or in your php change echo 'test'; to echo json_encode('test');
Hope this helps
You wrote dataType: 'json', so the PHP script is required to return valid JSON. Since you're not, the it gets an error when it tries to parse the response as JSON, and reports that error.
You should use json_encode:
<?php
echo json_encode('test');
?>
it should alert "test", but it calls error. What is going on?
Reason for this is your dataType : "json" in $.ajax() method which expects the response from serverside should be a json, which is not the case because that is just a simple text string nothing else, so what could you do:
Either remove the dataType or change the dataType: "text"
Or do a json_encode('string') at your serverside.
As you asked in your question
It should alert "test",
so you can skip the #2 and do this:
$.ajax({
type: 'POST',
url: 'test.php',
dataType: 'text',
data: {
godot: 'godot',
jobadze: 'jobadze'
},
success: function(data){
alert(data); // will alert "test".
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Error Status: "+textStatus+"\nMessage: "+errorThrown);
}
});
but it calls error
$.ajax({
type: 'POST',
url: 'test.php',
dataType: 'json', //<----because of this
See json is a {key : value} pair js object and from your php you are just echoing a string not a object.

Categories

Resources