I am trying to update a field with a small jquery script but it keeps returning an error and I cannot see where I have a problem.
I have an anchor with onclick="reportAd(MyAid)" that runs this:
function reportAd(aid) {
var conf = confirm("Will you report this ad?");
if(conf == true) {
$.ajax({
url: rootURL + '/reportad/',
type: 'PUT',
dataType: 'json',
contentType: 'application/json',
data: {'aid': ''+aid+''},
success: function(data) {
alert("Ad have been reported");
},
error: function(data) {
console.log(data);
}
});
}
return false;
}
Which should run this:
$app->put('/reportad/', function() use ($app, $adverts) {
$request = Slim::getInstance()->request();
$data = json_decode($request->getBody());
$adverts->report_ad($data->aid);
});
FireBug gives me this:
Object { readyState=4, status=200, statusText="OK"}
If I call the script with cURL
curl -i -X PUT -H 'Content-Type: application/json' -d '{"aid":"43"}' http://www.domain.dk/reportad/
it works.
You're asking the content of the answer to be parsed as JSON. If it's not JSON, then you're probably encountering a parseError.
Try to remove the dataType argument.
The standard approach to overcome lack of support for "PUT" is to use "POST" and to introduce a pseudo-PUT mechanism, on which the server-side code can branch.
For example :
$.ajax({
type: 'POST',
data: {method: 'PUT', 'aid': ''+aid+''},
});
Exactly what you do server-side depends on the language/framework you are using.
Related
$.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 try to make a post query to save my array in database. server side is PHP. My angular part:
$http({
method: 'POST',
url: "addOrder.php",
data: myJsonedArray,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
});
Angular make a post query to addData.php, but in php file my command
print_r($_POST); or print_r($_REQUEST);
give me empty Array();
How to fix it? Thanks
UPDATE:
if I try this example in jquery - I have he same result - empty array, but if I try with "test_var" - example works well:
$.post("addOrder.php", { "test_var": da }, function (data) {
console.log(data);
});
How to make the same result? I've tried
$http({
method: 'POST',
url: "addOrder.php",
data: { "test_var": da },
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
});
but no result (
Perhaps this helps: http://www.cleverweb.nl/javascript/a-simple-search-with-angularjs-and-php/
$data = file_get_contents("php://input");
$objData = json_decode($data);
Also, I find $resource much easier to use...
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.
I try searching about this but I just can't find any that can solve my problem. I want to produce a url like to this to send request to my webservice:
http://localhost/jQueryStudy/RamagalHTML/processjson3.php?
path=update%2FtallyHdr&json=
{"SessionID":"hHuCG3Jt1um5gV7kE320Bw7EjG97I4qZ","operation":"add",
"transaction_date":"2011-7-29","supplier_id":"10000000108","wood_specie_id":"1",
"lines":[{"plank_number":"7","thickness":"5","width":"8","length_t":"8","quantity":"1","board_foot":"26.67","wood_classification_id":"1","price":"15"}],"scaled_by":"WER","tallied_by":"WE","checked_by":"WE","total_bdft":"580.00","final":"N"}
Here's my current javascript code i have right now:
var dataJSON = {
"SessionID": $.cookie("SessionID"),
"operation": "add",
"transaction_date":$('#tallyDate').val(),
"supplier_id":$('#supplierInput').attr("name"),
"wood_specie_id":$('#woodSpecie').attr("name"),
"lines":plank_data,
"scaled_by":$('#tallyScaled').val().toUpperCase(),
"tallied_by":$('#tallyTallied').val().toUpperCase(),
"checked_by":$('#tallyChecked').val().toUpperCase(),
"total_bdft":$('#tallyTotal').val(),
"final":"N"
};
alert('this is the datajson from add : ' + JSON.stringify(dataJSON));
$.ajax({
type: 'POST',
data: dataJSON,
url: 'processjson2.php?path=update/tallyHdr',
dataType: primeSettings.ajaxDataType,
success: function(data) {
if ('error' in data)
{
showMessage('ERROR: ' + data["error"]["msg"]);
}
else{
$('#tblTallyHdr').trigger('reloadGrid');
}
}
});
My .php code is this:
<?php
$data_url = http_build_query (array('json' => $_REQUEST["json"]));
$data_len = strlen ($data_url);
echo file_get_contents("http://localhost:8001/" . $_REQUEST["path"], false, stream_context_create(
array (
'http' => array(
'method'=>'POST',
'header' => "Connection: close\r\nContent-Length: $data_len\r\n",
'content'=>$data_url
)
)
));
Evrytime I run my program, the url is only this http://localhost/jQueryStudy/RamagalHTML/processjson2.php?path=update/tallyHdr, the data was not posted which makes my request not executed. Please help me on this. I don't know how to fix my php.
If you're wanting all your data to be sent as part of the URL then you should use GET, not POST.
It's therefore possible to do away with the data property and append everything to the request URL:
$.ajax({
type: 'GET',
url: 'processjson2.php?path=update/tallyHdr&json='+dataJSON,
dataType: primeSettings.ajaxDataType,
success: function(data) {
if ('error' in data)
{
showMessage('ERROR: ' + data["error"]["msg"]);
}
else{
$('#tblTallyHdr').trigger('reloadGrid');
}
}
});
If you must use POST, then you just need to provide a variable name to go with your json:
$.ajax({
type: 'POST',
data: "json="+dataJSON,
url: 'processjson2.php?path=update/tallyHdr',
dataType: primeSettings.ajaxDataType,
success: function(data) {
if ('error' in data)
{
showMessage('ERROR: ' + data["error"]["msg"]);
}
else{
$('#tblTallyHdr').trigger('reloadGrid');
}
}
});
For more info, see the examples towards the end of the page: http://api.jquery.com/jQuery.ajax/
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";