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
Related
$.ajax({
type : 'POST',
url : '<?=site_url("aplikasi_tambah_merchant/input_merchant/get_mdr_master");?>',
data : 'kode='+arr_value[0],
beforeSend:function(){
$('#ajax-loader').show();
},
error: function(){
$('#ajax-loader').hide();
alert('Error\nGagal request data');
},
success: function(data){
var res = JSON.parse(data);
datamdr = Number(res.mdr_debit);
$('#ajax-loader').hide();
}
});
$.ajax({
type : 'POST',
url : '<?=site_url("pameran/update_mdr_pameran");?>',
data : 'datamdr='+datamdr+'&app_id='+app_id+'&on_off=2',
beforeSend:function(){
$('#ajax-loader').show();
},
error: function(){
$('#ajax-loader').hide();
alert('Error\nGagal request data');
},
success: function(data){
alert("tes "+datamdr);
alert("balik "+data);
$('#ajax-loader').hide();
}
});
this is the ajax code to send my data.
the first ajax is to get the value of datamdr = Number(res.mdr_debit);then i send datamdr value again to the controller, but in controller here
public function update_mdr_pameran() {
$this->config->set_item('compress_output', FALSE);
$datamdr = trim($this->input->post('datamdr'));
$app_id = trim($this->input->post('app_id'));
$on_off = trim($this->input->post('on_off'));
$out = $this->aplikasi_model->update_mdr_app_id_onoff($datamdr, $app_id, $on_off);
echo json_encode($datamdr);
}
those datamdr value is undefined, while the other 2 variable is still readable as string? how is it possible? i've tried parse the first json to string and int but still no luck to send the data again
Ajax works asynchronously by default so what is happening, is that both your requests execute at the same time and at that moment, the value you set on completion of the first ajax call, is still undefined.
You should wrap your second ajax call in a function and call that from the success handler in your first ajax call.
Or you combine both requests in one as they seem to be going to the same server any way.
A third option would be to make the ajax calls synchronous but that would block the execution of your script so I would not recommend that.
What #jeroen suggesting is this:
$.ajax({
type : 'POST',
url : '<?=site_url("aplikasi_tambah_merchant/input_merchant/get_mdr_master");?>',
data : 'kode='+arr_value[0],
beforeSend:function(){
$('#ajax-loader').show();
},
error: function(){
$('#ajax-loader').hide();
alert('Error\nGagal request data');
},
success: function(data){
var res = JSON.parse(data);
datamdr = Number(res.mdr_debit);
$('#ajax-loader').hide();
update_mdr_pameran();
}
});
function update_mdr_pameran(){
$.ajax({
type : 'POST',
url : '<?=site_url("pameran/update_mdr_pameran");?>',
data : 'datamdr='+datamdr+'&app_id='+app_id+'&on_off=2',
beforeSend:function(){
$('#ajax-loader').show();
},
error: function(){
$('#ajax-loader').hide();
alert('Error\nGagal request data');
},
success: function(data){
alert("tes "+datamdr);
alert("balik "+data);
$('#ajax-loader').hide();
}
});
}
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);
}
This is the result: [{"apn":"173-76-001"}]
From this code (php):
<?php
require_once('../config.php');
if(isset($_GET['parcel_id'])) {
$db = new ezSQL_mysql(DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);
$data = $db->get_results("select apn from parcels where parcel_id=" . $_GET['parcel_id']);
if($data != null) echo json_encode($data);
//if ($data != null) echo $data;
}
?>
jquery:
$('#searchTable tr').click(function(){
var parcel_id = $(this).attr('id');
alert(parcel_id);
$.ajax({
url: "classes/get-apn.php?id=" + parcel_id,
//timeout: 30000,
type: "GET",
error: function(SMLHttpRequest, textStatus, errorThrown){
alert("An error has occurred making the request: " + errorThrown);
},
success: function(data){
//do stuff here on success
alert(data);
$('#ParcelNumber').val(data);
}
});
});
How do I get the value of apn (173-76-001) into a label??
Im new at all this so thanks for your help in advance!!! :)
EDIT: So I tried the response below but it didn't work. I was told I need to parse using jQuery.parsJSON but it's not working either. I'm so confused. Here's my updated jQuery code:
$('#searchTable tr').click(function(){
var parcel_id = $(this).attr('id');
$('#ParcelId').html(parcel_id);
$.ajax({
url: "classes/get-apn.php?id=" + parcel_id,
//timeout: 30000,
type: "GET",
data: { parcel_id : parcel_id },
dataType: 'json',
error: function(SMLHttpRequest, textStatus, errorThrown){
alert("An error has occurred making the request: " + errorThrown);
},
success: function(data){
//do stuff here on success
var result = $.parseJSON(data);
alert(result.apn);
}
});
});
You perform the ajax request to the server. Server queries the DB and formats output as json. Ajax request hereby succeeded and the following line of code sets the label’s value:
$('#ParcelNumber').val(data);
Label ID here is ParcelNumber. To get the value you probably need to:
$('#ParcelNumber').val(data[0]["apn"]);
Whether ParcelNumber is not “valued” control (e.g. not an input but static div), use .html method:
$('#ParcelNumber').html(data[0]["apn"]);
I have a jQuery php script which accesses a database and echoes back html to fill a div on my page. It uses the following code.
function myCall() {
var request = $.ajax({
url: "ajax.php",
type: "GET",
dataType: "html"
});
request.done(function (msg) {
$("#divholder").html(msg);
});
request.fail(function (jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
}
What I need to do is also send a variable through to the script so it knows what to look for in the database. I have been searching but I can't seem to find quite the right answer. Any help greatly appreciated.
Regards.
With a get request just append it to the url.
$.ajax({
url : 'ajax.php?someVar=20',
type : 'GET',
dataType : 'html'
)}
You can also add it to the data property and jQuery will url encode your data and append it to the url string.
$.ajax({
url : 'ajax.php',
type : 'GET',
dataType : 'html',
data : {
someVar : 20
}
)}
You can send the parameter like this :
function myCall() {
var request = $.ajax({
url: "ajax.php?param1=" + 'parameter',
type: "GET",
dataType: "html"
});
request.done(function(msg) {
$("#divholder").html(msg);
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
}
And get the parameter with $_GET
Or you can send the parameter with POST (look at data : Ajax jQuery)
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)