Retorno Json PHP para Ajax em branco - php

I'm learning PHP and JS, and while doing a Get with Ajax, the PH return is coming in white. I'm turning the net but not finding anything, I'd like some help.
$idEvent = $_REQUEST["idEvent"];
$event = $this->model->getById($idEvent);
header('Content-type: application/json');
echo json_encode($event, JSON_PRETTY_PRINT);
exit;
$('#ShowEvent').click(function() {
var idEvent = document.getElementById("ShowEvent").getAttribute("idEvent");
$.ajax({
url: 'http://localhost/salgadar/public_html/Event/GetEventById',
type: 'get',
data: {
idEvent: idEvent
},
dataType: 'JSON',
success: function(data) {
alert('AJAX call was successful!');
$("#AjaxReturn").html(data)
},
error: function() {
alert('There was some error performing the AJAX call!');
}
});
console.log(data);
});
ReferenceError: data is not defined

First place the console.log() inside your ajax call, like this:
$.ajax({
url: 'http://localhost/salgadar/public_html/Event/GetEventById',
type: 'get',
data: {
idEvent: idEvent
},
dataType: 'JSON',
success: function(data) {
alert('AJAX call was successful!');
console.log(data); //HERE CODE
$("#AjaxReturn").html(data);
},
error: function() {
alert('There was some error performing the AJAX call!');
}
});
Then tell me what appears and we will continue to solve the problems.

Related

Unsuccessful Ajax to PHP post

My Ajax script keeps returning a result of unsuccessful. The console doesn't appear to show any errors. It just keeps throwing the alert window saying "error" instead of showing the result.
Ajax
$.ajax
({
url: 'query.php',
type: 'POST',
dataType:'json',
data: {Category: 'test'},
success: function(result)
{
if(result)
{
console.log(result);
alert(result);
}
},
error: function()
{
alert("error");
}
}); // end ajax call
php
$cat = $_POST['Category'];
echo $cat;
please check your query.php page. and make sure this page return some response either data or error massage like statusText="Error".
Do ajax function like below
$.ajax({ url: 'query.php',
type: 'POST',
dataType:'json',
data: {Category: 'test'},
success: function(result)
{
if(result.success=="TRUE")
{
console.log(result);
alert(result.cat);
}
},
error: function()
{
alert("error");
}
});
In query.php
$cat=$_POST['category'];
if(!empty($cat)){
$data['success']="TRUE";
$data['message'] = "Category Found.";
$data['cat']='$cat';
}
else{
$data['success'] = "False";
$data['message'] = "Category not found.";
}
die(json_encode($data));
jquery ajax document
option 1
response a json from php
example: echo "{}";
option 2
remove dataType: 'json'

How handle errors in php script fired by Jquery.ajax?

I have php-script, firing with jquery ajax function. Somthing like this:
$("a.test").click (function () {
var new_id = $(this).attr("new_id");
$.ajax({
url: 'test.php',
type: "POST",
cache: false,
async: true,
data: ({
new_id : new_id
}),
success: function (data) {
alert (data);
},
error: function(){
alert('error');
}
});
return false;
});
Now, a have some errors in test.php, but I can't see them. Sript just runs and I have no feedback, only error alert (alert ('error')).
How can I get back errors, that I have in test.php to handle them?
If you echo the errors in test.php, you can simply do:
$.ajax({
url: 'test.php',
type: "POST",
cache: false,
async: true,
data: ({
new_id : new_id
}),
success: function (data) {
alert (data);
},
error: function(data){
alert('error:'+data);
}
});
return false;
});
Edit:
I usually do something like this. In test.php if you get an error, create an array with your error info and echo it json encoded:
$message=array('error' => 1,'message' => '<div class="alert alert-danger" role="alert">' . $login['message'] . '</div>' );
echo json_encode($message);
Now in your jquery you can retrive the error by:
success: function (data) {
alert (data);
},
error: function(data){
var obj = JSON.parse(data);
alert(obj.message);
}
When you have it in array like this you dont even need error: function(data) anymore, since you can simply:
success: function (data) {
var obj = JSON.parse(data);
if (obj.error) {
// do something
alert (obj.message);
}else{
// do something else
}
},
On test.php you could show errors using the code explained here: https://stackoverflow.com/a/21429652/6525724
And then on this page instead of alert('error') you could use alert(data).
Try this
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}

return a json value from an mvc controller method in php

i would like to get an json type value from an mvc controller method. everything is correct but an error occures'.
my jquery ajax function:
function user_login(uname,pass){
$.ajax({
url: 'http://localhost/s/login_request',
type:'POST',
data:{uname:uname,pass:pass},
dataType:"json",
cache: false,
})
.done(function(response){
//do something
alert('1234');
})
.fail(function(jqXHR,textStatus){
alert(JSON.stringify(jqXHR));
});
}
and here is my php code(mvc controller method):
function login_request(){
header('Content-Type: application/json');
echo json_encode(array('testvalue'));
}
when i run the code, the .fail section executed and the following value was returned:
{"readyState":4,"responseText":"[\"testvalue\"]","status":200,"statusText":"OK"}
how can i solve this? thanks...
Try using
$.ajax({
url: 'http://localhost/s/login_request',
type:'POST',
data:{uname:uname,pass:pass},
dataType:"json",
cache: false,
success: function(data) { },
fail: function(xhr, status) { alert(JSON.stringify(xhr)) },
error: function() { },
complete: function() { alert('1234') }
});

ajax link json datatype call

I want to send the data via ajax to other page. I have isolated the problem. This is the code.
Thank you all for your help..But no effect..
updated code
It worked...
<script>
$(document).ready(function(){
$(".edit").click(function(event) {
event.preventDefault(); //<--- to prevent the default behaviour
var box = 1233;
var size=123;
var itemname=123;
var potency=123;
var quantity=12333;
var dataString ={
'box' :box,
'size':size ,
'itemname':itemname,
'potency':potency,
'quantity':quantity
};
$.ajax({
url: "dd.php",
type: "post",
data: dataString,
success: function(data) {
alert(data);
},
error: function(data) {
alert(data);
}
});
});
});
</script>
So I click the link,it navigates, to dd.php which has
<?php
echo json_encode(array('itemcode'=>$_POST['itemname']));
echo $_POST['itemname'];
?>
I get Object Object as alert. What am doing wrong? Pls throw some light here..thanks you..
$(document).ready(function(){
$(".edit").click(function(event) {
event.preventDefault();
var data = {"box":1233,
"size":565,
"itemname":565,
"potency":876,
"quantity":234};
$.ajax({
url: "dd.php",
type: "post",
data: data,
dataType: "json",
success: function(data) {
if(console){
console.log(data);
}
},
error: function(data) {
if(console){
console.log(data);
}
}
});
});
});
few things to consider... you can post data as object..which is clean and easier to use
$(".edit").click(function(event) {
event.preventDefault(); //<--- to prevent the default behaviour
var box = 1233;
....
var dataString ={'box':box,'size':size,'itemname':itemname,'potency':potency,'quantity':quantity};
$.ajax({
url: "dd.php",
type: "post",
data: dataString,
dataType: "json", //<--- here this means the response is expected as JSON from the server
success: function(data) {
alert(data.itemcode); //<--here alert itemcode
},
error: function(data) {
alert(data);
}
});
so you need to send the response as json in PHP
<?php
echo json_encode(array('itemcode'=>$_POST['itemname']))
?>
Here you are using querystring as sent in GET request.
If you want to send the data in same form, you can use this with GET request type:
$.ajax({
url: "dd.php"+dataString,
type: "get",
dataType: "json",
success: function(data) {
console.log(data);
alert(data.itemcode);
},
error: function(data) {
alert(data);
}
});
Or for POST request,you will have to put data in json object form, So you can use :
var dataString ={
'box' :box,
'size':size ,
'itemname':itemname,
'potency':potency,
'quantity':quantity
};
$.ajax({
url: "dd.php",
type: "post",
data: dataString,
dataType: "json",
success: function(data) {
console.log(data);
alert(data.itemcode);
},
error: function(data) {
alert(data);
}
});
});
And put echo in your php code :
<?php
echo json_encode(array('itemcode'=>$_POST['itemname']))
?>
Javascript alert shows [Object object] for object. You can see response using console.log or can use that key with alert.
For more information, refer jQuery.ajax()

How to run PHP script in the back by a jquery button

I need to run some PHP code from a file when I click a button from jQuery. This is the code I have:
$(document).ready(function(){
$("#btnSubmit").button().click(function(){
alert("button 1");
$.ajax({
url: 'releaseBackEnd.php',
type: 'POST',
async: false,
data: {},
dataType: 'xml',
error: function(){
alert('Error');
},
success: function(data){
//check error
alert("success!");
}
});
});
});
It shows the alert of "error". I have the releaseBackEnd.php file in the same directory of the javascript file.
check the response in firebug console .. if u don't have firebug add it to your firefox using this link
https://addons.mozilla.org/en-US/firefox/addon/1843/
Change
$("#btnSubmit").button().click(
to
$("#btnSubmit").click(
and check whether the php page is sending the response or not.
Try getting the error in the error callback function using the XMLHttpRequest.
error(XMLHttpRequest, textStatus) {
}
Try this code...
$(document).ready(function(){
$("#btnSubmit").bind('click',function() {
alert("button 1");
$.ajax({
url: 'releaseBackEnd.php',
type: 'POST',
async: false,
data: {},
dataType: 'xml',
error: function(){
alert('Error');
},
success: function(data){
//check error
alert("success!");
}
});
});
});

Categories