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);
}
Related
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.
Im trying to develop an android app using php, jquery, mysql and phonegap.
Phonegap environment don't let me use php, but I can locate it in to my server and I request data from database with ajax.
I can do simple queries, but when I use a var taken from $_POST, it doesn't works, exactly way isset($_POST['any_var']) returns false, but if I do isset($_POST) returns true, so I think I have an incorrect dataString.
I'm new in this kind of develop any clue in helpful.
<script>
$(document).ready(function()
{
$("#login").click(function(){
var nombre=$("#nombre").val();
var pass=$("#pass").val();
var dataString= "nombre="+nombre+"&pass="+pass+"&login=true";
if($.trim(nombre).length>0 & $.trim(pass).length>0){
$.ajax({
type: "POST",
url:"https://crm.inter-web.es/app/json.php",
data: dataString,
crossDomain: true,
cache: false,
beforeSend: function(){ $("#login").val('Conectando...');
},
success: function(data){
return data;
},
error: function(jqXHR, textStatus, errorThrown){ alert(errorThrown);}
});
var url="https://crm.inter-web.es/app/json.php";
$.getJSON(url, function(track){
console.log(track);
$(".list").append("<li>Nombre "+track['nombre']+"</li>");
$(".list").append("<li>Pass "+track['pass']+"</li>");
});
}return false;
});
});
</script>
PHP code:
<?php
//server code
include "db.php";
if (isset($_POST['login'])) {
$q=mysqli_query($con,"select nombre, pass from usuarios where nombre='".$_POST['nombre']."'");
$datos=mysqli_fetch_all($q, MYSQLI_ASSOC);
$num=mysqli_num_rows($q);
$json=json_encode($datos);
echo $json;
}else{
$q=mysqli_query($con,"select * from clientes where id_cliente='62' ");
$datos=mysqli_fetch_array($q, MYSQLI_ASSOC);
$num=mysqli_num_rows($q);
// var_dump($datos);
// for ($i=0; $i < $num ; $i++) {
// echo $datos[$i][0]."<br>";
// }
$json=json_encode($datos);
// mkdir("./json/");
// $fp=fopen("json/json.json", "w+");
// fwrite($fp,$json);
echo $json;
}
?>
Instead trying to format a "dataString"... I suggest you to use an object:
dataObject = {
nombre: $("#nombre").val(),
pass: $("#pass").val(),
login: true,
}
And in the ajax:
$.ajax({
type: "POST",
url:"https://crm.inter-web.es/app/json.php",
data: dataObject,
// ...
success: function(data){
// return data; // That line does nothing.
console.log(data);
},
Finally, I did this with GET in stead of POST, my first code was redundant, I did 2 request to the server:
$.ajax({
type: "POST",
url:"https://crm.inter-web.es/app/json.php",
data: dataString,
crossDomain: true,
cache: false,
beforeSend: function(){ $("#login").val('Conectando...');
},
success: function(data){
return data;
},
error: function(jqXHR, textStatus, errorThrown){ alert(errorThrown);}
});
AND:
$.getJSON(url, function(track){
console.log(track);
$(".list").append("<li>Nombre "+track['nombre']+"</li>");
$(".list").append("<li>Pass "+track['pass']+"</li>");
});
I modify the url with the GET parameters in the second way ("https://url?name=name&pass=pass") and it Works fine.
I'm trying to send some data from PHP back to AJAX. I found some examples but it doesn't seem to work. The result of console log is: "test: success". How can I get the data?
$.ajax({
url: "assets/psv.php",
method: "POST",
dataType: "HTML",
success: function(results, test){
console.log("test:" + test);
},
error : function (e) {
console.log("error " + e);
}
});
PHP
$test= "pgv";
echo $test;
Try:
$.ajax({
url: "assets/psv.php",
method: "GET",
success: function(data){
console.log("test:" + data);
},
error : function (e) {
console.log("error " + e);
}
});
or something like this:
$.get( "assets/psv.php", function( data ) {
alert( "Data Loaded: " + data );
});
The first variable in the success callback contains data received from the page you called.
PHP
header('Content-Type: application/json');
$test= "pgv";
echo json_encode($test);
JS
$.ajax({
url: "assets/psv.php",
method: "GET",
dataType: "json",
success: function(response, status){
console.log("test", response.data); //CHANGE THIS!!
},
error : function (e) {
console.log("error " + e);
}
});
data will contain
{
headers: "...",
data: "pgv",
....
}
I am trying to get my session in ajax.. for that i had written my code like this
BTLJ.ajax({
type: "POST",
url: btlOpt.BT_AJAX,
data: datasubmit,
success: function(html){
//if html contain "Registration failed" is register fail
BTLJ("#btl-register-in-process").hide();
if(html.indexOf('$error$')!= -1){
...
...
}
}else{
BTLJ(".btl-formregistration").children("div").hide();
BTLJ("#btl-success").html(html);
BTLJ("#btl-success").show();
alert(<?php session_start(); print_r($_SESSION); ?>);
setTimeout(function() { ); BTLJ(".kcregbox").show();},7000);
// BTLJ("#btl-success").hide();
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus + ': Ajax request failed');
}
});
but ajax is not working if i write like that.. please help me in getting my session in ajax. thanks in advance.
Your AJAX query in Joomla should be formatted as below.
jQuery.post('index.php',{
'option' : 'com_componentname',
'controller' : 'controllername',
'task' : 'task_name',
'format' : 'raw',
'data' : data
}).success(function(result) {
//if the request is success
}).error(function() {
//if the request is fails
});
I'm using this format for ajax in joomla
$.ajax({
type: 'GET',
url: 'index.php',
data: {option: 'com_componenetname', task: 'taskname.youroperation', format: 'json', tmpl: 'raw'},
dataType: 'json',
async: true, // can be false also
error: function(xhr, status, error) {
console.log("AJAX ERROR in taskToggleSuceess: ")
var err = eval("(" + xhr.responseText + ")");
console.log(err.Message);
},
success: function(response){
// on success do something
// use response.valuname for server's data
}
,
complete: function() {
// stop waiting if necessary
}
});
In your component/controllers you should have a file yourcontroller.json.php which will process your call and return encoded json array will all the data you need in the client
I have a problem:
I have a JS function which sending data to php script, then PHP script returning JSON data from database QUERY and I want to get values returned from PHP script.
<script type="text/javascript">
<!--
jQuery('#wysz2').submit(function() {
var myData = {
"rodzaj_konta": jQuery('#rodzaj_konta').val(),
"miejscowosc": jQuery('#miejscowosc').val()
};
jQuery.ajax({
url: 'http://somescript.php?action=results',
type: 'GET',
data: myData,
dataType: 'json',
beforeSend: function() {
jQuery('#loading').html('<p>loading...</p><img src="loading.gif" />'); //Loading image during the Ajax Request
},
error: function(xhr, textStatus, errorThrown) {
alert("Error: " + (errorThrown ? errorThrown : xhr.status));
},
contentType: "application/json; charset=utf-8",
success: function(data) {
alert(data);
}
});
return false;
});
//-->
</script>
The PHP script returning data in proper format using:
header('Content-Type: application/json');
echo json_encode($data);
When I'm trying to alert(data), I get always a null.
How to get this returned JSON data ?
EDITED:
It's strange, because I have changed sending method to POST.
PHP returning JSON:
[{"nazwa":"Test","nazwa_firmy":"Testowa","ulica":null,"numer_domy":"2A","numer_mieszkania":"11","kod_pocztowy":"00-189","miejscowosc":"Warszawa","telefon":"213-123-132","nip":"112-312-31-31","regon":"231232133","adres_www":"http:\/\/www.gogl.epl","rodzaj_uzytkownika":"serwis"}]
But my JQUERY AJAX Script still returning null.
So my script now looks like this:
<script type="text/javascript">
<!--
jQuery('#wysz2').submit(function() {
var myData = {
rodzaj_konta: jQuery('#rodzaj_konta').val(),
miejscowosc: jQuery('#miejscowosc').val()
};
jQuery.ajax({
url: 'http://somedomain.com/skrypt.php?action=wyniki_wyszukiwania',
type: 'GET',
data: myData,
dataType: 'json',
contentType: "application/json; charset=utf-8",
jsonp: "jsoncallback",
beforeSend: function() {
jQuery('#loading').html('<p>ładowanie...</p><img src="loading.gif" />');//Loading image during the Ajax Request
},
error: function (xhr, textStatus, errorThrown) {
alert("Error: " + (errorThrown ? errorThrown : xhr.status));
},
success: function (data) {
alert(JSON.stringify(data));
console.log(data);
}
});
return false;
});
//-->
</script>
Any ideas ?
you are constructing your variables while sending in a wrong way semicoluns for object names is not there according to definitions
try this
var myData = {
rodzaj_konta: jQuery('#rodzaj_konta').val(),
miejscowosc: jQuery('#miejscowosc').val()
};
and while alerting your json data try
alert(JSON.stringify(your_json_obj));
Try to alert the object of the result...
Means if json in the format {"responseCode":"001","responseMsg":"success"}
Then alert data.responseCode
In success of your ajax function try something like this
var objParams1 = $.parseJSON(data);
console.log(objParams1);
alert(objParams1.Testowa)