here is my store code:
var sql = Ext.create('Ext.data.Store', {
model: 'SQL',
groupField: 'project',
proxy: {
type:'ajax',
api: {
read: 'data/showText.php', // Called when reading existing records
update: 'data/saveRollout.php' // Called when updating existing records
},
actionMethods: {
read : 'GET',
update : 'POST'
},
reader: {
type: 'json',
root: 'data'
},
writer: {
type: 'json'
}
},
autoSync: true,
autoLoad: true
});
It sends right json code
{
"projectId":102,
"project":"2G Rollout and Performance",
"taskId":123,
"description":"2)Capacity Sites Delta",
"january":123,
"february":0,
"march":0,
"april":0,
"may":0,
"june":0,
"july":0,
"august":0,
"september":0,
"october":0,
"november":0,
"december":0,
"id":null
}
But there is NULL on response in php file
var_dump(json_decode($_POST, true));// shows NULL on response
You are actually sending your data to the server via the request body, not via the url.
Using:
$iRequestBody = file_get_contents('php://input');
Will work.
See similar issue and some (additional) excellent answers.
Have you tried taking out:
writer: {
type: 'json'
}
To see if it handles regular text sent to the server, maybe your server is not handling the JSON encoding well.
Related
In the middle of a PayPal Checkout Express (client-side) javascript, I need to use AJAX to call the output of a PHP page, but I'm a bit stuck.
The PHP page:
$data = array('retid' => $username);
header('Content-Type: application/json');
echo json_encode($data);
Now inside the other javascript page I simply want to capture the PHP variable $username, via AJAX, as a javascript variable.
<?php
$IDToPassPlus = ($id.'&retid=');
?>
<script>
//It's the inclusion of this part, which tries to get the "retid" js variable, that stops the script from rendering the Paypal button:
$.ajax({
type: 'POST',
url: 'test-call.php',
dataType: 'json',
success: function(response) {
var retid = response.data.retid;
},
});
paypal.Button.render({
env: 'sandbox',
client: {
sandbox: 'xxxxx',
production: 'xxxxx'
},
commit: true,
style: {
layout: 'vertical',
size: 'responsive',
shape: 'rect',
color: 'gold'
},
payment: function(data, actions) {
return actions.payment.create({
payment: {
transactions: [
{
amount: { total: '0.99', currency: 'GBP' }
}
],
redirect_urls: {
'cancel_url': 'pay-return-cancel.php?id=<?php echo $IDToPassPlus; ?>'+retid
}
}
});
},
onAuthorize: function(data, actions, error) {
return actions.payment.execute().then(function() {
window.alert('Payment Complete!');
window.location.replace('test-return.php?id=<?php echo $IDToPassPlus; ?>'+retid);
if (error === 'INSTRUMENT_DECLINED') {
actions.restart();
}
});
},
onCancel: function(data, actions) {
return actions.redirect();
},
onError: function(err) {
window.location.replace('pay-return-error.php?id=<?php echo $id; ?>'+retid);
}
}, '#paypal-button');
</script>
Without the contributor's AJAX suggestion, the button works perfectly. But I'm trying to pass a variable from a PHP page by way of AJAX, to add it onto the redirects.
it's possible to use on in-page javascript as
<script>
var js_var = "<?php echo $php_var;?>";
//now you have php var value in javascript to use on .php page
If it's not what you are seeking, then please elaborate your question.
ok so as far I understood you want to retrieve the PHP response via ajax and you don't know how to make ajax call. Here is an example you may use on your js file:
$.ajax({
type: 'POST',
url: 'YOUR PHP SCRIPT URL',
dataType: 'json',//this will make it understand what datatype to expect in response
success: function(response) {
var retid = response.data.retid; //here you get on successfull response
},
});
First, read this entire page; it will really help you throughout your career as a developer, it has helped me tremendously: https://stackoverflow.com/help/mcve
Then, lets use the knowledge gained from that page to make an MCVE. Put this on a new page:
$.ajax({
type: 'POST',
url: 'test-call.php',
dataType: 'json',
success: function(response) {
var retid = response.data.retid;
console.log(retid);
},
});
This should print the value of retid to your console. Take a look at your console. Notice any errors, or does the value of retid print as expected?
So why have we taken time to create a new page and put this on it? We are narrowing down our issue, we're trying to find the exact cause of the problem by creating an MCVE. If we don't know what is causing the problem, and if we can't create a very basic example to illustrate the problem, we will have a hard time solving the problem and/or asking for help.
(Note 1, make your code "pretty" when you post it here. Indent it as it should be indented; this makes it easier for others to read. You are asking people to take time out of their day to help you, for free; make it as easy as possible for them to read and understand your code)
(Note 2, here is an example of where I had some very, very complicated MySQL interactions that I had a question about. Rather than post all of the complicated code, I followed the MCVE concept: DRY - how to extract repeated code to...a stored function maybe? and made some fake, very very simplified examples of my problem. Since I did that, I was able to get quick, concise answers from experts, notice the answer I accepted was from one of the top-scored users on all of Stackoverflow)
Good day. I have an unsettling error that I've encountered recently and I do not know where it came from or how it came about.
I have a form where I want to save data to the database upon button press which is handled by the controller. This is what I do in my controller:
var personStore = Ext.getStore('personBaseDetails');
var caStore = Ext.getStore('creditApplication');
var form = button.up('form').getForm();
var userId = personStore.first().get('ID');
//use this to update
if(caStore.count() < 1){
var creditApplication = Ext.ModelManager.create({
}, 'appName.model.creditApplicationModel');
caStore.add(creditApplication);
}
var record = caStore.first();
form.updateRecord(record);
console.log("user id to be edited is = " + userId);
console.log("caStore count = " + caStore.getCount());
caStore.getProxy().extraParams = {
selectedUserID: userId
};
// caStore.load();
caStore.sync({
success: function(batch) {
console.log(batch.operations[0].request.scope.reader.jsonData['message']);
},
failure: function(batch) {
console.log(batch.operations[0].request.scope.reader.jsonData['message']);
}
});
Here, I set the store extra param in order to use it in the php code query. However, the issue I have is that when I get the selectedUserID in the php code I have, I couldn't seem to get the extra parameter. If I commented out the if(isset($_GET['selectedUserID'])){ .... }, the query works (though the values are hardcoded as of now).
Here is what my store looks like:
Ext.define('app.store.creditApplication', {
extend: 'Ext.data.Store',
requires: [
'app.model.creditApplicationModel',
'Ext.data.proxy.Ajax',
'Ext.data.reader.Json',
'Ext.data.writer.Json'
],
constructor: function(cfg) {
var me = this;
cfg = cfg || {};
me.callParent([Ext.apply({
autoLoad: false,
model: 'app.model.creditApplicationModel',
storeId: 'creditApplication',
clearOnPageLoad: false,
proxy: {
type: 'ajax',
api: {
create: 'data/person/creditApplication/createCreditApplication.php',
read: 'data/person/creditApplication/readCreditApplication.php',
update: 'data/person/creditApplication/updateCreditApplication.php'
},
url: '',
reader: {
type: 'json',
root: 'data'
},
writer: {
type: 'json',
encode: true,
root: 'data'
}
}
}, cfg)]);
}
});
Now I'm dumbfounded since I have another code which is similar in the sense that I set the extraParam in the controller and the php code was able to receive and read it just fine. Note that both my stores do not have any extraParam property.
I've been stuck with this problem and I don't know how to go about it. Any help would be greatly appreciated.
Store does not have extraParam(s), proxy does. You can set it with:
store.getProxy().setExtraParam(name, value)
I have seen many examples, but for whatever reason, none seem to work for me.
I have the following sent from a app, via ajax, to a php file. This is how it looks when its sent:
obj:{"ClientData":
[{
"firstName":"Master",
"lastName":"Tester",
"email":"me#me.com",
"dob":"1973-01-22",
"age":"51",
}],
"HealthData":
[
"condition : Prone to Fainting / Dizziness",
"condition : Allergic Response to Plasters",
],
"someData":
[{
"firstName":"Male",
"lastName":"checking",
}]
}
Code as is:
{"ClientData":[{"firstName":"Master","lastName":"Tester","email":"me#me.com","dob":"1973-01-22","age":"51","pierceType":"Vici","street":"number of house","city":"here","county":"there","postcode":"everywhere"}],"HealthData":[["condtion : Prone to Fainting / Dizziness","condtion : Allergic Response to Plasters","condtion : Prone to Fainting / Dizziness"]],"PiercerData":[{"firstName":"Male","lastName":"checking","pierceDate":"2013-02-25","jewelleryType":"Vici","jewelleryDesign":"Vidi","jewellerySize":"Vici","idChecked":null,"medicalChecked":null,"notes":"This is for more info"}]}
This comes in one long line into a php file, here is the code:
<?php
header('Content-Type: application/json');
header("Access-Control-Allow-Origin: *");
//var_dump($_POST['obj']);
$Ojb = json_decode($_POST['obj'],true);
$clientData = $Ojb['ClientData'];
$healthData = $Ojb->HealthData;
$someData = $Ojb->someData;
print_r($clientData['firstName']);
?>
No matter what I have tried, I am unable to see any of the information, I don't even get an error, just blank! Please can someone point me in the right direction.
Thank you :)
UPDATE
Here is the code that creates the object:
ClientObject = {
ClientData : [
{
firstName : localStorage.getItem('cfn'),
lastName : localStorage.getItem('cln'),
email : localStorage.getItem('cem'),
dob : localStorage.getItem('cdo'),
age : localStorage.getItem('cag'),
pierceType : localStorage.getItem('cpt'),
street : localStorage.getItem('cst'),
city : localStorage.getItem('cci'),
county : localStorage.getItem('cco'),
postcode : localStorage.getItem('cpc')
}
],
HealthData : health,
PiercerData : [
{
firstName : localStorage.getItem('pfn'),
lastName : localStorage.getItem('pln'),
pierceDate : localStorage.getItem('pda'),
jewelleryType : localStorage.getItem('pjt'),
jewelleryDesign : localStorage.getItem('pjd'),
jewellerySize : localStorage.getItem('pjs'),
idChecked: localStorage.getItem('pid'),
medicalChecked: localStorage.getItem('pmh'),
notes: localStorage.getItem('poi')
}
]
};
And here is how its sent:
function senddata() {
$.ajax({
url: 'http://domain.com/app.php',
type: 'POST',
crossDomain: true,
contentType: "application/json; charset=utf-8",
dataType: 'jsonp',
data: 'obj='+JSON.stringify(ClientObject),
success : function(res) {
console.log(res);
},
error: function(err) {
}
});
}
There are a few things that will cause problems:
why dataType: 'jsonp'? If you don't intend to utilize jsonp, don't instruct jQuery to do this. See the docs: https://api.jquery.com/jQuery.ajax/
"jsonp": Loads in a JSON block using JSONP. Adds an extra
"?callback=?" to the end of your URL to specify the callback. Disables
caching by appending a query string parameter, "_=[TIMESTAMP]", to the
URL unless the cache option is set to true.
'obj='+JSON.stringify(ClientObject), this will guarantee invalid json.
For reference, have a look at this question: jQuery ajax, how to send JSON instead of QueryString on how to send json with jquery.
That said, try the following:
function senddata() {
$.ajax({
url: 'app.php',
type: 'POST',
crossDomain: true,
contentType: 'application/json; charset=utf-8"',
data: JSON.stringify(ClientObject),
success : function(res) {
console.log(res);
},
error: function(err) {
}
});
}
And in app.php use
$input = json_decode(file_get_contents('php://input'));
to get the data. Use it like:
var_dump($input->ClientData[0]->firstName); // => string(6) "Master"
$Ojb = json_decode($_POST['obj'],true);
makes it array so u need to get them using array index instead of object
UPDATE1
With your update here how it could be done
$str ='{"ClientData":[{"firstName":"Master","lastName":"Tester","email":"me#me.com","dob":"1973-01-22","age":"51","pierceType":"Vici","street":"number of house","city":"here","county":"there","postcode":"everywhere"}],"HealthData":[["condtion : Prone to Fainting / Dizziness","condtion : Allergic Response to Plasters","condtion : Prone to Fainting / Dizziness"]],"PiercerData":[{"firstName":"Male","lastName":"checking","pierceDate":"2013-02-25","jewelleryType":"Vici","jewelleryDesign":"Vidi","jewellerySize":"Vici","idChecked":null,"medicalChecked":null,"notes":"This is for more info"}]}' ;
$obj = json_decode($str,true);
echo $obj["ClientData"][0]["firstName"];
You can get other elements as above
UPDATE2
You are sending the data as JSONP and this will make the request as
?callback=jQuery17108448240196903967_1396448041102&{"ClientData"
Now you are also adding data: 'obj=' which is not correct.
You can simply send as json not jsonp
and on the php file you can do as
$Ojb = json_decode(file_get_contents('php://input'),true);
I didn't understand well the idea behind of proxies in ExtJS. Can I use simple functions with them in order to read and save data using only one url? Such as when I want to read data: users.read() and when I want save the new and edited fields of a grid: users.save() ?
yes you can use functions as users.save() and users.read() and this functions will use urls which you provide for these methods in Proxy.
proxy: new Ext.data.HttpProxy({
api: {
create:{
url: '/users/create',
method: 'POST'
},
read: {
url: '/users/read',
method: 'POST'
},
update: {
url: '/users/update',
method: 'POST'
},
destroy: {
url: '/users/delete',
method: 'POST'
}
}
}),
or
proxy : new Ext.data.HttpProxy({
method: 'GET',
prettyUrls: false,
url: 'local/default.php',
api: {
// all actions except the following will use above url
create : 'local/new.php',
update : 'local/update.php'
}
}),
I don't think I could answer your question any better than if you were to read the following article.
Sencha > Learn > The Data Package
I have a simple checkbox, on click it sends XHR to PHP page , php processes correctly and I use json_encode($response) to return. But instead of a simple true or false I get the source code for the page and it is causing a "parsererror" of course.
ajax call as follows
$.ajax({
type: "post",
url: "myprocessor.php",
dataType: 'json',
data: { "id" : idnumber, "action": "makeLive", "isLive" : "1" },
beforeSend: function(data) {
$("#ajaxInProgress").addClass('progress');
},
success: function(data) {
$("#status").removeClass().addClass((data.error === true) ? 'error' : 'success').text('Success! Appraiser is NO LONGER Live ').slideDown('slow');
},
error: function(data) {
$("#status").removeClass().addClass('error').text(' - Changing the Live status for this appraiser to "Not Live" has failed - APPRAISER IS STILL LIVE IN SYSTEM, please try again').slideDown('slow');
},
complete: function(data) {
$("#ajaxInProgress").removeClass('progress');
setTimeout(function() {
$("#status").slideUp('slow').removeClass();
},2000);
}
});
The php I post to is as follows:
if (isset($_POST['action'])) {
if($_POST['action']=='makeLive') {
$checkappraiser=mysql_query("SELECT * FROM table WHERE id='".mysql_real_escape_string($_POST['id'])."'");
if (mysql_numrows($checkappraiser)>0) {
$livesetting=mysql_result($checkappraiser,0,"live");
$livesetting=!$livesetting;
$runSql = mysql_query("UPDATE table SET live='$livesetting' WHERE id='".mysql_real_escape_string($_POST['id'])."'");
if(!$runSql) {
$return['error'] = true;
} else {
$return['error'] = false;
}
}
}
echo json_encode($return);
}
Any suggestions would be great.
I am getting the proper data passed
I am getting the correct data updated in DB
My response is coming back as a parser error because it is trying to parse the source code as a json array.
Just a quick check, do you put <?php at the beginning of your php file?
That, or you're doing something wrong in your webserver, not passing files through to php correctly. Does hitting the php file directly load the source or the result?
If you hit page.php, does it load the same thing as if you hit page.phP or pHP, etc? It matters to web server filters, depending on the web server...
If you use tomcat for java, for example... you can turn off case sensitivity for finding files, but it does not turn off case sensitivity for mapping files to filters or servlets, so .jsp would load the jsp servlet, but .jsP would not.