crossrider how to collect post data with php - php

So I am finding it difficult to post data to my php server. It seems to work from the crossrider end of things, but I am not sure what to use to collect the post with PHP.
Here is the crossrider code borrowed from the docs page:
appAPI.ready(function($) {
// Posting data using a JSON object
appAPI.request.post({
url: 'http://ultimarks.arcco96.c9.io/service.php',
// Data to post
postData: ["hello","world"],
onSuccess: function(response) {
//alert("Succeeded in posting data");
//alert(response);
},
onFailure: function(httpCode) {
//alert('Failed to retrieve content. (HTTP Code:' + httpCode + ')');
},
additionalRequestHeaders: {
myHeader: 'value'
},
contentType: 'application/json'
});
});
and this is my php code:
print_r($_post);
It returns Array() on both the php page and in an alert generated by crossrider (which is strange because I never programmed that).
Perhaps the problem is that I am trying to print something to a PHP page that's not a redirect from a form.
So how do I fix this problem?

Variables in PHP are case-sensitive. The correct PHP variable is $_POST not $_post

appAPI.ready(function($) {
var data1 = "Mydata1";
var data2 = "Mydata2";
appAPI.browserAction.onClick(function() {
appAPI.request.post({
url: 'http://www.example.com/Ext.php',
postData: 'data1='+ data1 +'&data2='+ data2,
onSuccess: function(response) {
alert("Succeeded in posting data");
//alert(response);
},
onFailure: function(httpCode) {
alert('in posting data. (HTTP Code:' + httpCode + ')');
},
additionalRequestHeaders: {
myHeader: 'value'
},
// contentType: 'application/json'
contentType: 'application/x-www-form-urlencoded'
});
}); });
Then, in the Ext.php file grab the post data using $_POST["data1"] and $_POST["data2"]
Sample code for $_POST[]:
http://www.w3schools.com/php/php_post.asp

PHP $_POST global variable does not get populated from JSON payload in requests. So, either you send data in x-www-form-urlencoded as retailcoder is suggesting, or modify the way your php scripts reads the input, as found here: POST JSON data via CURL and grabbing it

Related

Get elements of a array sended by Post from Jquery in Php

I have this Problem and because I am very fresh in this subject I don't know how to procedure. I want to read the Content of a Array variable sended from Jquery by Post to the Server Php. Then I could separate the values and send differents query to the DB
This is what I have:
var Content = {};
var subcontent= {};
var key;
$("table tr.data").each(function(i) {
var row = [];
key = $(this).find('td').eq(0).find('input').val();
row.push($(this).find('td').eq(1).text());
row.push($(this).find('td').eq(2).text());
row.push($(this).find('td').eq(5).text());
subcontent[key] = row;
});
Content['.select'.val()] = subcontent;
var ContentJSON= JSON.stringify(Content);
$.ajax({
data: ContentJSON,
url: 'page.php',
type: 'POST',
dataType: 'json',
beforeSend: function (){
alert('Information wird gespeichert');
},
success: function (r) {
$("#resultado").html(r);
alert('Information wurde gespeichert');
},
error: function(){
alert('Fehler ..');
}
});
How is the procedure in Server side with PHP to read the Content of this variable.
Can please somebody help me?
You need to use this :
$post = file_get_contents('php://input');
You will get the content of your JSON.
Check this answer for more details : Get all variables sent with POST?
Not quite sure what it is your asking. I guess you're sending the Json data to the file page.php? Could you show the code for the page.php file?
Also, please not ethat success and error are deprecated as of jQuery 1.8, I would suggest the .done(), .fail() and .always() callbacks instead, implementing the $.post() method
$.post( 'page.php' )
.done(function(data) {
alert( "success" );
})
.fail(function(data) {
alert( "error" );
})
.always(function(data) {
alert( "complete" );
});
You can handle the data that gets returned from your page.php file if you pass it in the callback.
If you show me what's happening server side, it would help me understand.
Michael

Ajax submit post data to a get url

Is it possible to mix post and get in ajax? Specifically have a form POST data to a url with get variables?
In html and PHP I would normally do this:
<form action="script.php?foo=bar" method="POST">
...insert inputs and buttons here...
</form>
And the PHP script would handle it based on logic/classes.
I have tried the following and several variations to no avail:
$(document).ready(function() {
$('#formSubmitButton').click(function() {
var data = $('#valueToBePassed').val();
$.ajax({
type: "POST",
//contentType: 'application/json',
url: "script.php?foo=bar",
data: data,
processData: false,
success: function(returnData) {
$('#content').html( returnData );
}
});
});
});
Is this even possible? If so what am I doing wrong. I do not feel as if I am trying to reinvent the wheel as it is already possible and used regularly (whether or not if it is recommended) by plenty of scripts (granted they are php based).
Please check out the below jsfiddle URL and
https://jsfiddle.net/cnhd4cjn/
url: "script.php?data="+data, //to get it in the URL as query param
data:"data="+data, // to get it in the payload data
Also check the network tab in dev tools to inspect the URL pattern on click of the submit button
You can, here's what I do.
$(document).ready(function() {
$('#formSubmitButton').click(function() {
// My GET variable that I will be passing to my URL
getVariable = $('#valueToBePassed').val();
// Making an example object to use in my POST and putting it into a JSON string
var obj = {
'testKey': 'someTestData'
}
postData = JSON.stringify(obj);
// Jquery's AJAX shorthand POST function, I'm just concatenating the GET variable to the URL
$.post('myurl.com?action=' + getVariable, postData, function(data) {
JSONparsedData = $.parseJSON(data);
nonparsedData = data;
});
});
});
I can see 1 syntax error in you code .
use
data: {data:data},
instead of
data: data,
and then try to access like
$_POST['data']; and $_GET['foo'];
But i have never tried the GET params inside a POST request :) , this is only a suggestion.

jQuery Ajax(post), data not being received by PHP

The Ajax function below sends data from a page to the same page where it is interpreted by PHP.
Using Firebug we can see that the data is sent, however it is not received by the PHP page. If we change it to a $.get function and $_GET the data in PHP then it works.
Why does it not work with $.post and $_POST
$.ajax({
type: "POST",
url: 'http://www.example.com/page-in-question',
data: obj,
success: function(data){ alert(data)},
dataType: 'json'
});
if there is a problem, it probably in your php page.
Try to browse the php page directly in the browser and check what is your output.
If you need some inputs from post just change it to the GET in order to debug
try this
var sname = $("#sname").val();
var lname = $("#lname").val();
var html = $.ajax({
type: "POST",
url: "ajax.class.php",
data: "sname=" + sname +"&lname="+ lname ,
async: false
}).responseText;
if(html)
{
alert(html);
return false;
}
else
{
alert(html);
return true;
}
alax.class.php
<php
echo $_REQUEST['sname'];
echo $_REQUEST['sname'];
?>
Ajax on same page will not work to show data via POST etc because, PHP has already run that's why you would typically use the external page to process your data and then use ajax to grab the response.
example
success: function(){
$('#responseDiv').text(data);
}
You are posting the data... Check if the target is returning some data or not.
if it returns some data then only you can see the data otherwise not.
add both success and error.. so that you can get what exactly
success: function( data,textStatus,jqXHR ){
console.log(data);//if it returns any data
console.log(textStatus);//or alert(textStatus);
}
error: function( jqXHR,textStatus,errorThrown ){
console.log("There is some error");
console.log(errorThrown);
}

$_POST not being set with AJAX call

This should be a fairly simple call but I just can't seem to make it work. Basically, I'm trying to pass a set of search parameters to a PHP script but $_POST is coming up empty. The call (via jQuery)...
self.search = function () {
var data = {
'year': 2013,
'month': 10,
'day': 1
};
$.ajax({
dataType: 'json',
type: 'POST',
url: 'repositories/blogposts.php',
data: { 'search': data },
success: function(results) {
// populate knockout vm with results...
}
});
};
The PHP code waiting to do something with the incoming json object...
if (isset($_POST['search'])) {
echo find_blogposts(json_decode($_POST['search']));
}
I've tried this many ways but no matter what, print_r($_POST) gives me an empty array. What's missing?
PHP is probably choking on the object you are trying to send.
You should either send the data object directly:
data: data,
(to get $_POST['year'], etc. in php)
or convert the object to a json string you can decode on the php side:
data: { 'search': JSON.stringify(data) },
What does happen inside of find_blogposts()?
Alternatively you could try .post().
$.post( "repositories/blogposts.php", { year: "2013", month:"10", day:"1" }, function( data ){
// do something here
});
In your php just receive $_POST['year'] which will be 2013.
Hope it helps.
Here is api doc for .post()

Sending JSON to server, using jQuery

I am trying to send simple data to theservre, and I need a "rough and ready" way to do this.
This is what I have so far:
var emails = ['a#123.com', 'b#123.com', 'c#123.com'];
var ruff_json = "{ 'emails': [";
for (i in emails)
ruff_json += ((i == 0) ? '' : ', ') + '\''+emails[i]+'\'';
ruff_json += '] }';
jQuery.ajax({
type: 'POST',
url: '1.php',
data: ruff_json,
dataType: "json",
timeout: 2000,
success: function(result){
//do something
},
error: function (xhr, ajaxOptions, thrownError){
//do something
}
});
Using Firebug, I can see that the data is POSTed to the server - however, at the server, there is no data ($_POST is empty) - what am I doing wrong?
We post all of our data with json.
var myobj = { this: 'that' };
$.ajax({
url: "my.php",
data: JSON.stringify(myobj),
processData: false,
dataType: "json",
success:function(a) { },
error:function() {}
});
then in php we do
<?php
$json = json_decode(file_get_contents("php://input"), true);
// Access your $json['this']
// then when you are done
header("Content-type: application/json");
print json_encode(array(
"passed" => "back"
));
?>
This way we don't even mess with the post variables, and in general, its faster than having jQuery process them.
Your data field should contain an object with key-value pairs, because it gets encoded as POST key-values pairs.
data = {my_json: encoded_string};
Then on the PHP side you can access the data as:
$data = json_decode($_POST['my_json']);
PHP populates $_POST by parsing the data received. However, it only knows form-encoded data, JSON data cannot be parsed automatically. So $_POST will be useless in this case. You need to get the raw post data and parse it with json_decode.

Categories