I am trying to make a post request from my angular js, as below
var postData={
firstName:'VenuGopal',
lastName:'Kakkula'
};
postData=JSON.stringify(postData);
$http({method:'POST',url:'http://localhost/blog/posttest.php?insert=true',data:postData,headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
.success(function (data,status,headers,config) {
alert('Success' + data);
})
.error(function (data, status,headers,config) {
// uh oh
alert('error' + status + data);
});
I am not sure how to read this POST DATA in my PHP REST webservice.
<?php
header("Access-Control-Allow-Origin:*");
header('Access-Control-Allow-Headers:Content-Type');
header("Content-Type:application/json");
if(!empty($_GET['insert']))
{
$result=json_decode($_POST['firstName']);
deliver_response(200,"Got the Post data","GotData $result");
}
function deliver_response($status,$statusmsg,$data)
{
header("HTTP/1.1 $status $statusmsg");
$response['status']=$status;
$response['status_message']=$statusmsg;
$response['data']=$data;
$json_response=json_encode($response);
echo $json_response;
}
?>
I tried the below options
json_decode($_POST['firstName'])
json_decode($_POST['data'])
json_decode($_POST['[postData'])
None of them returned the data, Its always returning the error Undefined index: firstName in F:\xampp\htdocs\Blog\posttest.php on line 10
Can anybody help me how I can read the POST request data sent in php file.
Most likely it is because you are submitting JSON data which is not automagically populated into the $_POST variable per standard form data.
The work around is to manually parse the input into a variable for use.
Example:
<?php
$args = json_decode(file_get_contents("php://input"));
echo $args->firstName;
?>
You can also solve this problem without changing code in server and use $_POST the regular way. Explained here: http://victorblog.com/2012/12/20/make-angularjs-http-service-behave-like-jquery-ajax/
Related
I have an ajax-script that retrieves jsondata from php - so far ok, but the data could not be parsed since other outputs (echoes) comes along with the jsonstring. I searched this issue and it seems one should add header information when sending relevant output (json) from php back to clientside (ajax). When I do that nothing is sent back. How could I solve this?
this is how it looks like on the client side retrieving json (together with other prints)
connected to database { jsondata comes here .. } success
So, how to isolate the jsondata sending it back?
clientside (ajax) , snippet
$(function(){
$.ajax({
type:'POST',
url: 'endpoint.php?function=getJson',
data: {name: 'Stockholm'},
success: function (data){
console.log('success',data);
var jsonData = JSON.parse(data); //error here when parsing!!!
serverside (php), snippet
//header('Content-Type: application/json'); //if I add thos row no data is sent back
$result = $_GET['function']($_POST['name']);
echo $result;
function getJson($name) {
...
return $json;
}
I solved the problem by cleaning stdout (output buffer), putting the function call just a line before echo $result
that is:
$result = $_GET['function']($_POST['name']);
ob_clean(); // this call solved the problem
echo $result;
source:
https://www.php.net/manual/en/function.ob-clean.php
I am using Fetch Api in my application.
I've got a PHP server page to get session data which was already defined before. It seemd like this:
<?php
header('Content-Type: application/json; charset=UTF-8');
header('Access-Control-Allow-Origin: *');
session_start();
// $_SESSION['data'] already defined before
$result = array();
// print_r($_SESSION['data']);
if (isset($_SESSION['data'])) {
$result = $_SESSION['data'];
$result['code'] = 'ok';
} else {
$result['code'] = 'error';
}
echo json_encode($result, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
I also got another html page to get the session data. It seemd like this:
<script>
$(function() {
// use $.ajax
$.ajax({
url: 'session.php',
dataType: 'json'
})
.done(function(res) {
console.log(res);
});
// end
// use fetch
fetch('session.php').then(function(res) {
if (res.ok) {
res.json().then(function(obj) {
console.log(obj);
});
}
});
// end
});
</script>
The problem is, when I use $.ajax(), session data can be correctly showed. But when I use fetch(), the session data was undefined.
So, what goes wrong and how can I fix it? Thanks!
If you want fetch to send cookies, you have to provide the credentials option.
See https://developer.mozilla.org/en-US/docs/Web/API/GlobalFetch/fetch#Parameters for details.
jquery ajax is a usual ajax request and the browser is sending the cookie header with the session id that identify your session.
fetch doesnt - instead a new session is created with out any data
send the php session id either with url or header
have a look at: http://php.net/manual/en/session.idpassing.php
Im creating a validation form in Ajax and PHP. But i don't have a clue how i should get the value from PHP??
For example:
The validation form is in index.php And the page with the function is checkUser.php.
In checkUser i have a global file included with my classes initialized. The checkUser.php look like this:
<?php
$requser = false;
require "core/rules/glb.php";
$user->checkUser($_GET['username']);
The get function comes from the Ajax call i do in the index file. But how do i know that PHP said that the username already exist så that i can make a if statement and paus the script?
Im a beginner, thanks.
And sorry for my english
$.ajax({
type: "GET",
url: "user_add.php",
data: 'username='+$("#jusername").val()+'&email='+$("#jemail").val()+'&password='+$("#jpassword").val()+'&secureSession=23265s"',
success: function()
{
location.href='register.php';
}
});
Jus print out the data, for better help also post the ajax script
<?php
$requser = false;
require "core/rules/glb.php";
print $user->checkUser($_GET['username']);
If you are trying to give a response to the ajax call from php, then you can do it via normal output. Just like
echo json_encode(array("status"=>"FAIL"));
exit();
will send a json response to the ajax call from the php script. like
{"status":"FAIL"}
which you can parse it at the ajax callback and check the status. like
var data = JSON.parse(response);
if(data.status == "FAIL") {
alert("Ajax call returned failed");
}
Well, another try:
this is all the jquery code i'm using maybe i made something wrong in the code before $.post(); i call the following function with the onclick of the same form...
function setLogin()
{
$('#login-form').submit(function(e) {
e.preventDefault();
//passing form field to vars
var formUsername=$("#login-form #username").val();
var formPassword=$("#login-form #password").val();
//checks on fields lenght
if((formUsername.length<6))
{
$("#ajax-output").html("<div class='error'>Attenzione username troppo breve!</div>");
}
else if((formPassword.length<6))
{
$("#ajax-output").html("<div class='error'>Attenzione password troppo breve!</div>");
}
else
{
$.post(
//the url
'?module=login',
//data got from login form
{
"username": formUsername,
"password": formPassword,
},
//response
function(data){
$("#ajax-output").html(data.reply)
},
//type
"json"
);
}
});
}
i tried with only this code in php file and it still doesn't return anything...
function Login()
{
//just to try
echo json_encode(array('reply'=>'foo'));
}
it still doesn't work...
Are you sure the post is being run in the first place?
Use Firebug! (or chrome's built-in developer tools)
You can use firebug to pick apart every bit of a web page.
It has a "net" tab that shows every request that is made by the browser, including AJAX requests, and their results, headers and contents.
Use it to see if your requests is really being made, and what the result is. Then take it from there.
Make sure that you're setting a header for the content type when responding - the browser may not attempt to use the JSON if it doesn't know it's receiving JSON.
function Login()
{
header('Content-Type: application/json');
echo json_encode(array('reply'=>'foo'));
}
I am trying to create a little ajax chat system (just for the heck of it) and I am using prototype.js to handle the ajax part.
One thing I have read in the help is that if you return json data, the callback function will fill that json data in the second parameter.
So in my php file that gets called I have:
header('Content-type: application/json');
if (($response = $acs_ajch_sql->postmsg($acs_ajch_msg,$acs_ajch_username,$acs_ajch_channel,$acs_ajch_ts_client)) === true)
echo json_encode(array('lastid' => $acs_ajch_sql->msgid));
else
echo json_encode(array('error' => $response));
On the ajax request I have:
onSuccess: function (response,json) {
alert(response.responseText);
alert(json);
}
The alert of the response.responseText gives me {"lastid": 8 } but the json gives me null.
Anyone know how I can make this work?
This is the correct syntax for retrieving JSON with Prototype
onSuccess: function(response){
var json = response.responseText.evalJSON();
}
There is a property of Response: Response.responseJSON which is filled with a JSON objects only if the backend returns Content-Type: application/json, i.e. if you do something like this in your backend code:
$this->output->set_content_type('application/json');
$this->output->set_output(json_encode($answer));
//this is within a Codeigniter controller
in this case Response.responseJSON != undefined which you can check on the receiving end, in your onSuccess(t) handler:
onSuccess:function(t) {
if (t.responseJSON != undefined)
{
// backend sent some JSON content (maybe with error messages?)
}
else
{
// backend sent some text/html, let's say content for my target DIV
}
}
I am not really answering the question about the second parameter of the handler, but if it does exist, for sure Prototype will only provide it in case of proper content type of the response.
This comes from Prototype official :
Evaluating a JavaScript response
Sometimes the application is designed
to send JavaScript code as a response.
If the content type of the response
matches the MIME type of JavaScript
then this is true and Prototype will
automatically eval() returned code.
You don't need to handle the response
explicitly if you don't need to.
Alternatively, if the response holds a
X-JSON header, its content will be
parsed, saved as an object and sent to
the callbacks as the second argument:
new Ajax.Request('/some_url', {
method:'get', onSuccess:
function(transport, json){
alert(json ? Object.inspect(json) : "no JSON object");
}
});
Use this functionality when you want to fetch non-trivial
data with Ajax but want to avoid the
overhead of parsing XML responses.
JSON is much faster (and lighter) than
XML.
You could also just skip the framework. Here's a cross-browser compatible way to do ajax, used in a comments widget:
//fetches comments from the server
CommentWidget.prototype.getComments = function() {
var commentURL = this.getCommentsURL + this.obj.type + '/' + this.obj.id;
this.asyncRequest('GET', commentURL, null);
}
//initiates an XHR request
CommentWidget.prototype.asyncRequest = function(method, uri, form) {
var o = createXhrObject()
if(!o) { return null; }
o.open(method, uri, true);
o.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
var self = this;
o.onreadystatechange = function () {self.callback(o)};
if (form) {
o.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
o.send(makePostData(form));
} else {
o.send('');
}
}
//after a comment is posted, this rewrites the comments on the page
CommentWidget.prototype.callback = function(o) {
if (o.readyState != 4) { return }
//turns the JSON string into a JavaScript object.
var response_obj = eval('(' + o.responseText + ')');
this.comments = response_obj.comments;
this.refresh()
}
I open-sourced this code here http://www.trailbehind.com/comment_widget