Data send in json is change while send it - php

$.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();
}
});
}

Related

Passing a variable to PHP with jQuery and $.ajax

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)

PHP to jQuery - catching the json

Here's what I want to do. User submits form (a single text input) and send to PHP. PHP returns this;
{"status":"true","custid":"00001","custname":"John"}
I know that it is in JSON format, but I don't know how to catch and use the value so I can us the returned values.
$(function(){
$('#icnumber-form').submit(function(){
var icno = $('#icnumber').val();
var purl = 'php/create_process.php'
$.ajax({
type : 'POST',
url : purl,
cache : false,
data : icno,
dataType: 'json',
success : function(response){
var json = $.parseJSON(response);
alert(json.message);
},
beforeSend:function(){
$('.cust-exist-view').show();
}
});
return false;
})
});
Since you set the dataType to json, the response comes back as an already parsed object, so you don't try to parse it yourself.
success : function(response){
alert(response.status);
},
You don't need to use var json = $.parseJSON(response); because jQuery automatically parse the JSON string to object . Just use it as a javascript object to access the json properties. I create a simple demo from your code. View it in jsfiddle
JS Code:
$(function () {
$('#icnumber-form').submit(function () {
//var icno = $('#icnumber').val();
var purl = '/echo/json/'
$.ajax({
type: 'POST',
url: purl,
cache: false,
data: {
json: '{"status":"true","custid":"00001","custname":"John"}',
delay: 1
},
dataType: 'json',
success: function (response) {
alert( "status:" + response.status
+ "\ncustname:"+response.custname
+ "\ncustid:"+ response.custid);
},
beforeSend: function () {
// $('.cust-exist-view').show();
}
});
return false;
})
});
SO you just need to view this part to see how to use json return :
success: function (response) {
alert( "status:" + response.status //access status
+ "\ncustname:"+response.custname //access custname
+ "\ncustid:"+ response.custid); // access custid
},

Getting JSON in PHP from jQuery .ajax()

I'm having trouble getting JSON data sent from JavaScript to PHP. Here is my Javascript:
var noteData = {
nData: {
"postID": $postID,
"commentPar": $commentPar,
"commentValue": $commentValue
}
}
var sendData = JSON.stringify(noteData);
$.ajax({
type: "POST",
url: templateUrl+"/addnote.php",
data: sendData,
dataType : 'json',
success: function(data) {
alert(data);
console.log(sendData);
},
error: function(e) {
console.log(e.message);
console.log(noteData);
console.log(sendData);
alert("error");
}
});
Here is how I just test if the data is even being passed to PHP, it always returns back null.
<?php
$nData = json_decode($_POST['nData']);
echo json_encode($nData);
?>
What am I doing wrong?
You are sending the data as raw JSON to PHP, not as POST parameter.
There are two alternatives. The first one leaves your PHP intact:
var noteData = {
nData: {
"postID": $postID,
"commentPar": $commentPar,
"commentValue": $commentValue
}
}
var sendData = JSON.stringify(noteData);
$.ajax({
type: "POST",
url: templateUrl+"/addnote.php",
data: {
nData: sendData
},
dataType : 'json',
success: function(data) {
alert(data);
console.log(sendData);
},
error: function(e) {
console.log(e.message);
console.log(noteData);
console.log(sendData);
alert("error");
}
});
The second one modifies the PHP side alone. You need to read the input stream directly to obtain the raw data.
<?php
$nData = json_decode(file_get_contents('php://input'));
echo json_encode($nData);
This one might be slightly different depending on the server configuration. See the documentation on the input stream wrappers.
Tell your post request that you are sending json object
contentType: "application/json"

How to Write PHP in AJAX

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

How to get JSON vars from PHP script

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)

Categories