I am trying to pass some data to a web-service using JQuery. Here is a simple client:
<script type="text/javascript">
$(function () {
$.ajax({
type: "POST",
url: "webservices/gammeList.php?lang=fr",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: onSuccess,
error: onError
});
});
function onError(result) {
alert("error");
}
function onSuccess(result){
alert(JSON.stringify(result));
}
</script>
And a simple server:
<?php
if (isset($_GET['lang']) && !empty($_GET['lang'])) {
$lang = $_GET['lang'];
} else {
$lang = "en";
}
echo (json_encode($lang));
?>
It is working properly, but I would like to pass the data using the data setting that way:
$(function () {
$.ajax({
type: "POST",
url: "webservices/gammeList.php",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: {lang: "fr"},
success: onSuccess,
error: onError
});
});
I always get "en" as a response from the web-service. So here, should I use the same method $_GET['lang'] to access the input data? What am I doing wrong?
EDIT:
I changed $_GET['lang'] in $_POST['lang'] but still, it doesn't work.
You can use server side $_REQUEST which will work for both POST and GET method:
$_REQUEST['lang']
You are using $_GET["Key"] which is incorrect as you are passing data in POST variables.
You can use either $_REQUEST["key"]
$lang = $_REQUEST["lang"];
or $_POST["key"]
$lang = $_POST["lang"];
to retrieve the data sent to the PHP script.
To read a little bit more about these refer links given below.
$_REQUEST
$_POST
So then use server side $_POST, not $_GET:
$_POST['lang']
You should pass array to json_encode function like,
<?php
// Also you are using post method in ajax so use $_POST or $_REQUEST here
if (isset($_REQUEST['lang']) && !empty($_REQUEST['lang'])) {
$lang = $_REQUEST['lang'];
} else {
$lang = "en";
}
echo (json_encode(array($lang)));// here passing array to json_encode
?>
After changing $_GET['lang'] in $_POST['lang'], it was still not working. I deleted the following line:
contentType: "application/json; charset=utf-8"
using then the default value 'application/x-www-form-urlencoded; charset=UTF-8' and it worked.
Related
I need to call php and get data from another server and I am using proxy.php to call from ajax.
proxy.php
<?
header('Content-type: application/json');
$url=$_GET['url'];
$json=file_get_contents($url);
echo $json;
?>
And my code looks
function scanFunction(){
var url="http://address/scan.php?user=user1&video=video1";
console.log(url);
url = 'proxy.php?url='+url;
$.ajax({
url: url,
type: "POST",
data: {
},
dataType: "JSON",
success: function (jsonStr) {
if(jsonStr.length>0){
var obj = jsonStr;
console.log(obj);
}
else{
console.log(" error...");
}
}
});
}
And this code works fine when I use one parameter to the url passing to proxy.php where as second argument missing
That is
echo $url; inside proxy.php print
http://address/scan.php?user=user1
event I pass two argument like,
proxy.php?url="http://address/scan.php?user=user1&video=video1"
That is second argument video missing inside proxy.php and so I am not getting expected result.
You may be having issues with your GET variables in the GET['url'] variable.
Try encoding your url when you send it to proxy.php to avoid such issues.
var url = encodeURIComponent("http://address/scan.php?user=user1&video=video1");
url = 'proxy.php?url='+url;
Then on the PHP side you need to decode it.
$url=$_GET['url'];
if (is_string($url)) {
$url = urldecode($url);
}
proxy.php cannot know which arguments are meant for it, and which are meant for scan.php. Eg, When you call url:
proxy.php?url=http://address/scan.php?user=user1&video=video1
Your proxy scripts thinks that the query parameters are:
url:"http://address/scan.php?user=user1"
video:"video1"
But your intent was for everything after url to be one parameter. A better approach is to use POST parameters instead of URL query parameters.
$.ajax({
url: url,
type: "POST",
data: {
resource_url: "http://address/scan.php?user=user1&video=video1"
},
....
});
Now, in proxy.php:
<?php
header('Content-type: application/json');
$url=$_POST['resource_url'];
$json=file_get_contents($url);
echo $json;
?>
Use the data: property of the ajax call to pass as much or as many parameters as you like
function scanFunction(){
$.ajax({
url: 'proxy.php',
type: 'POST',
data: {
url: 'http://address/scan.php',
user: 'user1',
video: 'video1'
},
dataType: "JSON",
success: function (jsonStr) {
if(jsonStr.length>0){
var obj = jsonStr;
console.log(obj);
} else {
console.log(" error...");
}
}
});
}
Then build whatever you want from those parameters in the php script
Oh and you used type: 'POST' in your javascript, so you should be using the $_POST array in your PHP script.
proxy.php
<?php
$url = $_POST['url'] . '?user=' . $_POST['user'] . '&video=' . $_POST['video'];
$json=file_get_contents($url);
header('Content-type: application/json');
echo $json;
?>
$.ajax({
url: '/gateway/',
type: 'POST',
data: {test : 'test'},
dataType: 'json',
}).done(function(){
console.log('done');
});
Above is my AJAX post, below is my PHP:
var_dump($_POST['test']);
die();
The problem is, this fails to work (I get a NULL value) - why?
I know my call is getting to the PHP code as I can dump any old string:
var_dump('hello');
die();
Where am I going wrong?
Just remove this dataType: 'json'. Your $_POST['test'] is a string value, not a JSON string.
The POST value that you are testing with is not JSON, it's a string.
Remove the
dataType: 'json',
and it should work.
When you set dataType: "json" within the AJAX request it means the expected response should be parsed as json, (not the outgoing POST, as others have said).
Heres is a stripped down copy&paste example, for you to build upon. Hope it helps
<?php
//is it POST
if($_SERVER['REQUEST_METHOD'] == 'POST'){
// set var
$test = isset($_POST['test']) ? $_POST['test'] : null;
//do some logic - skip that bit ;p
//was the request from AJAX, ok send back json
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
//always a good idea
header('Content-Type: application/json');
//json encode, notice the ABC, then look at the jQuery below
die(json_encode(
array('ABC' => 'From Response: '.$test)
));
}
}
?>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script>
jQuery(document).ready(function(){
var ajax = $.ajax({
url: "./",
type: "POST",
data: {test : 'test'},
dataType: "json"
});
ajax.done(function(data) {
$("#result").html(data.ABC); /* << See data is an object */
});
ajax.fail(function(xhr, status, error) {
$("#result").html(xhr.responseText);
});
});
</script>
<span id="result"></span>
I'm not totally sure if this is the issue, but .done is deprecated. Additionally, as others mentioned, you are asking for json from the server and not receiving json.
Your code should look like this
$.ajax({
url: '/gateway/',
type: 'POST',
data: {test : 'test'},
success: function () {console.log('done');}
});
I would like to recommend you my code. and please do check the following points.
check the location of the url you are giving. If it is in parent directory then you can access it using ../ and the most important thing give the extension of the file. like 'gateway.php'
and write success and failure function. It gives a better insight of what's going on.
$.ajax({
type:'POST',
url:'gateway',
data:{test:'test'},
success: function(data){
if(data)
{
alert(data);
}
},
failure: function(){
alert(failed);
}
}) ;
comment if there are any errors
hope it helps :). If it does then don't forget to green it :P
Or change PHP code
header('Content-Type: application/json');
exit(json_encode(array('data' => 'Bla bla bla')));
I have this ajax code
$.ajax(
{
type: "POST",
url: "getData.php",
data: ValueToPass,
cache: false,
success: function(html)
{
LastDiv.after(html);
}
});
I am new with this Ajax thing.
This code is to load getData.php file and send variables through type POST.
The variables are in this var ValueToPass = "lastid="+LastId+"&br="+br;.
Other thing this code does is return the getData.php's HTML after loading.
Probably with this. success: function(html)
How can I return this $br variable from getData.php after loading, so I can use it again through the next cycle. Cuz what happens here is that I can put the variable in the getData.php with the Ajax and working with it, but when the file getData.php is loaded, outside this file, the variable is not known(not declared). And I'm losing the counting :S
I want to return the HTML and the variable.
You can return json data in your php file like
$response = array ('br'=> $br, 'html'=> $html);
echo json_encode($response);
Here both html and data are returned.
And this to use it in your ajax callback :
success: function(data)
{
br = data.br;
LastDiv.after(data.html);
}
I'd consider setting a Session variable with the value from the $br variable passed via AJAX. Then when you call getData.php from another file or location, you can use the Session variable since session variables retain their value anywhere in the session.
You can try this to get the data from your `getData.php' :
$.ajax(
{
type: "POST",
url: "getData.php",
data: { ValueToPass: ValueToPass},
cache: false,
success: function(data)
{
LastDiv.html(data);
}
});
and in your getData.php you have to pass ValueToPass
maybe like this:
$ValueToPass = mysqli_real_escape_string($db, $_POST['ValueToPass']);
If I understand your question correctly, and if you want to return the $br variable then include it in a JSON object in the successs callback function. So, something like this (I'm not familiar enough with PHP so my PHP syntax might be incorrect):
// create JSON object
<?php
$result = array('br' => $br, 'html' => 'htmlContent);
echo json_encode($result);
?>
// return JSON object
$.ajax(
{
type: "POST",
url: "getData.php",
data: ValueToPass,
cache: false,
success: function(result)
{
var $br = result.br;
LastDiv.after(result.html);
}
});
I have the following variable in Javascript. I want to know how to pass this data to a PHP so that I can display the contents of the data once redirected.
postData = {
'dates_ranges': datesAndRanges,
'action':'build',
'output_type': output_type,
'form_html': formHtml,
'width': formBuilder.width(),
'rules':validationRules,
'theme': theme,
};
Use JQuery post method to pass data to PHP file:
$.post("/path/to/script.php", postData, function(result) {
// work with result
});
In PHP use $_POST global to get the variables:
print $_POST['dates_ranges'];
print $_POST['action'];
// ...
using jquery it goes easy & clean like this:
$.post('script.php', postData, function(response){
// process/display the server response
});
you can use:
$.post("YOUR_URL", postData, function(response) {
// handle with response
});
OR:
$.ajax({
url: YOUR_URL,
data: postData,
type: 'post',
success: function(response) {
// handle with response
}
});
And In your PHP file:
if(isset($_POST) && !empty($_POST)) {
$d = $_POST;
echo $d['date_range']; // and so more
}
I need (recently) to get an array from the server after an ajax call created by jquery. I know that i can do it using JSON. But i don't know how to implement it with JQuery (im new with JSON). I try to search in internet some example, but i didnt find it.
This is the code :
// js-jquery function
function changeSponsor() {
$.ajax({
type: 'POST',
cache: false,
url: './auth/ajax.php',
data: 'id=changespon',
success: function(msg) {
// here i need to manage the JSON object i think
}
});
return false;
}
// php-server function
if((isset($_POST['id'])) && ($_POST['id']=="changespon")) {
$linkspon[0]="my ";
$linkspon[1]="name ";
$linkspon[2]="is ";
$linkspon[3]="marco!";
echo $linkspon;
}
in fact, i need to get the array $linkspon after the ajax call and manage it. How can do it? I hope this question is clear. Thanks
EDIT
ok. this is now my jquery function. I add the $.getJSON function, but i think in a wrong place :)
function changeSponsor() {
$.ajax({
type: 'POST',
cache: false,
url: './auth/ajax.php',
data: 'id=changespon',
dataType: 'json',
success: function(data) {
$.getJSON(url, function(data) { alert(data[0]) } );
}
});
return false;
}
Two things you need to do.
You need to convert your array to JSON before outputting it in PHP. This can easily be done using json_encode, assuming you have a recent version of PHP (5.2+). It also is best practice for JSON to use named key/value pairs, rather than a numeric index.
In your jQuery .ajax call, set dataType to 'json' so it know what type of data to expect.
// JS/jQuery
function changeSponsor() {
$.ajax({
type: 'POST',
cache: false,
url: './auth/ajax.php',
data: 'id=changespon',
dataType: 'json',
success: function(data) {
console.log(data.key); // Outputs "value"
console.log(data.key2); // Outputs "value2"
}
});
return false;
}
// PHP
if((isset($_POST['id'])) && ($_POST['id']=="changespon")) {
$linkspon["key"]= "value";
$linkspon["key2"]= "value2";
echo json_encode($linkspon);
}
1) PHP: You need to use json_encode on your array.
e.g.
// php-server function
if((isset($_POST['id'])) && ($_POST['id']=="changespon")) {
$linkspon[0]="my ";
$linkspon[1]="name ";
$linkspon[2]="is ";
$linkspon[3]="marco!";
echo json_encode($linkspon);
}
2) JQUERY:
use $.getJSON(url, function(data) { whatever.... } );
Data will be passed back in JSON format. IN your case, you can access data[0] which is "my";