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",
....
}
Related
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);
}
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
Checked several topics here on stack overflow and the jquery documentation but still getting stuck.
I basically want this to post (with ajax/jquery) to update a div's content.
function loadSubCats(value)
{
$.post("load_sub_cats.php",
data: { "catid": value },
type: "POST",
contentType: "application/x-www-form-urlencoded",
function(data) {
$('#sub_categories').html("Data Loaded: " + data);
});
}
But im getting no responses what so ever. The page contains the sub_categories div, and this is called onclick for a form event.
<select name='cselect3' onChange='loadSubCats(this.value)' class='e1'>
So basically, it should past the value of the field (cselect3) and load_sub_cats.php should just echo $_POST[catid]; thats it. But im getting zero activity on it so it think its something simple i've screwed up.
you have a problem with $.post syntax. Here's how it should be:
function loadSubCats(value)
{
$.post("load_sub_cats.php",{ "catid": value },
function(data) {
$('#sub_categories').html("Data Loaded: " + data);
});
}
as simple as it is.
function loadSubCats(value)
{
$.post("load_sub_cats.php",
{ catid: value },
function(data) {
$('#sub_categories').html("Data Loaded: " + data); }
);
}
You send catid not "catid"
You're mixing the syntax of $.post and $.ajax which are different. If you want to use the object syntax then call $.ajax, because $.post takes its arguments as a simple un-named list.
function loadSubCats(value)
{
$.ajax({
url : "load_sub_cats.php",
data: { "catid": value },
type: "POST",
contentType: "application/x-www-form-urlencoded",
success: function(data) {
$('#sub_categories').html("Data Loaded: " + data);
}
});
}
You could also directly attach the change event instead, of inline and do away with the loadSubCats() function:
$(document).ready(function(){
$('select[name=cselect3]').change(function(){
$.ajax({
url : "load_sub_cats.php",
data: { "catid": $(this).val() },
type: "POST",
contentType: "application/x-www-form-urlencoded",
success: function(data) {
$('#sub_categories').html("Data Loaded: " + data);
}
});
});
});
two things:
you are using type in post which is not required.
Even after removing it is not working just try to alert it-
function loadSubCats(value)
{
$.post("load_sub_cats.php",
data: { "catid": value },
type: "POST",
contentType: "application/x-www-form-urlencoded",
function(data) {
alert(data)
$('#sub_categories').html("Data Loaded: " + data);
});
}
By alert you will come to know -
1) if there is any php error it will alert that,
2) If php is working fine that it will alert with your values.
updating my post as per latest comments:
Try to use like below:
$(document).ready(function() {
$('.e1').change(function() {
$.post("load_sub_cats.php",
data: { "catid": value },
type: "POST",
contentType: "application/x-www-form-urlencoded",
function(data) {
alert(data)
$('#sub_categories').html("Data Loaded: " + data);
});
})
});
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)
I can get Ajax to send the request successfully but I want it to also redirect to the new page and it's not redirecting. Could anyone suggest an alternative method or correct way to redirect?
submitHandler: function(form) {
$("div.error").hide();
$.ajax({
type: "POST",
url: '<?php echo base_url().'subscribe/process_payment/'?>',
data: $(form).serialize(),
success: function(msg){
console.log( "Data Saved: " + msg );
},
error: function(msg){
console.log( "Error: " + msg);
}
});
return true;
},
Usually you can simply do the redirect in the success function
success: function(msg){
console.log( "Data Saved: " + msg );
window.location = "mysite.com/newURL";
},
or return the url
success: function(url){
window.location = url;
},