I am trying to write a script that allows posting to a JSON file. For some reason the process is succeeding, but the JSON file isn't being written to.
Here is my jQuery code:
$(function() {
var data = {
name: 'cool',
drink: 'cool2',
};
$.ajax({
type: "POST",
url: '/api/orders',
dataType: 'json',
async: false,
data: JSON.stringify(data),
success: function() {
alert("Thanks!");
}
})
});
Here is my JSON code (/api/orders)
[
{"id":1,"name":"Ben","drink":"Americano w/ Creme"},
{"id":2,"name":"Ben2","drink":"Americano w/ Creme2"},
{"id":3,"name":"Ben3","drink":"Americano w/ Creme3"}
]
I can't figure out why Chrome is saying it is succeeding, but the code isn't posting to the JSON file.
The problem isn't with your JavaScript. The JSON.stringify just concerts the data to a JSON string and passes it to the url. Your problem will be in the Url that it is posted to /Ali/orders. That looks like a directory to me instead of an API to handle the string. I could be wrong in that as certain technologies hide that stuff. Still you need to look at where the data is going to.
Related
I'm trying to implement a custom suggestion engine using jquery.
I take the user input, call my codeigniter v2 php code in order to get matches from a pre-built synonyms table.
My javascript looks like this:
var user_str = $("#some-id").val();
$.ajax({
type: "POST",
url: "http://localhost/my-app/app/suggestions/",
data: {"doc": user_str},
processData: false
})
.done(function (data)
{
// Show suggestions...
});
My PHP code (controller) looks like this:
function suggestions()
{
$user_input = trim($_POST['doc']);
die("[$user_input]");
}
But the data is NOT posted to my PHP :( All I get as echo is an empty [] (with no 500 error or anything)
I've spent 2 days looking for an answer, what I've read in SO / on google didn't help. I was able to make this work using GET, but then again, this wouldn't work with unicode strings, so I figured I should use POST instead (only this won't work either :()
Anyone can tell me how to fix this? Also, this has to work with unicode strings, it's an important requirement in this project.
I'm using PHP 5.3.8
Try using the $.post method, then debug. Do it like this:
JS
var user_str = $("#some-id").val();
var url = "http://localhost/my-app/app/suggestions";
var postdata = {doc:user_str};
$.post(url, postdata, function(result){
console.log(result);
});
PHP
function suggestions(){
$user_input = $this->input->post('doc');
return "MESSAGE FROM CONTROLLER. USER INPUT: ".$user_input;
}
This should output the message to your console. Let me know if it works.
For those interested, this works for me, even with csrf_protection being set to true
var cct = $.cookie('csrf_the_cookie_whatever_name');
$.ajax({
url: the_url,
type: 'POST',
async: false,
dataType: 'json',
data: {'doc': user_str, 'csrf_test_your_name': cct}
})
.done(function(result) {
console.log(result);
});
I've been searching around, but I cannot find an answer, my guess is that my question is not defined very well, so i hope to get some guidance
I'm using turbogears2.2
I'm sending from the client view a JavaScript object through $.post(),
On the server I receive this object (as kw):
{'phones[1][surname]': u'sym', 'phones[2][name]': u'', 'phones[1][phone]': u'5498498', 'phones[0][phone]': u'0564', 'phones[1][name]': u'jhon', 'phones[0][surname]': u'cat', 'phones[2][phone]': u'', 'phones[0][name]': u'bob'}
I'm sending a data from a table with 3 columns
On my server I'm trying to separate the data for each row, but I'm a bit lost here.
how can I split that dict into different rows of data?
Doing
import json
json.loads(str(kw))
Fails
{ValueError}: Expecting property name: line 1 column 2 (char 1)
How can I convert that dict/object to a nested dictionary (or something else)?
Thanks
Thanks for the help Martijn Pieters , I thought I was posting JSON, but i wasn't.
You didn't post JSON; you posted application/x-www-form-urlencoded data that jQuery formatted for the PHP array feature. – Martijn Pieters
Here is my JavaScript, I'm trying out HandsOnTable (jQuery data grid editor)
$("#sendToServer").click(function(){
var tableData = $("#myTable").data('handsontable');
$.post(
URL,
{phones:tableData.getData()},
function(data){
console.log(data)
}
)
})
And that wasn't JSON, even though I thought it was
Anyway, simple fix:
Client side (JavaScript):
var tableData = $("#myTable").data('handsontable');
var jsonData = JSON.stringify(tableData.getData())
...
$.post(URL,
{phones:jsonData},
...
)
And now on the server side (Python):
import json
def getPhones(self,**kw):
phones = json.loads(kw['phones'])
...
And I have the data as a dict of rows, great
Thanks for the guidance
To post JSON, don't use $.post(). Use $.ajax() instead, and set the content type explicitly:
$.ajax({
url: URL,
type: "POST",
data: JSON.stringify({phone: tableData.getData()}),
contentType: 'application/json; charset=utf-8'
dataType: 'json',
success: function(data) {
console.log(response);
},
});
This can especially help if you have a controller that handles JSON directly, such as those provided by TurboGears Web Services.
So I have a form, AND I have a KnockoutJs app, with a CakePHP back end. When I hit Cake's default "save" button, I'm wanting to spit out and post a JSON along with the standard form data.
Here's what I have in my JS so far:
$('input.saveProgram').click(function() {
var theJson = ko.mapping.toJSON(pvm, mapping);
$.ajax({
url: 'http://localhost/cake/programs/edit',
dataType: 'json',
type: 'POST',
data: theJson
});
});
In Cake, I'm trying to use the the Request handler in my controller, but to no avail:
if($this->RequestHandler->setContent('json', 'application/json')) {
// standard saving code
}
In my Cake app I've tried die($this->request->data) to see what's going on and the JSON doesn't seem to be posting at all.
Here's a solution as I interpret your question. In your controller:
if($this->RequestHandler->isAjax()){
// "spit" out json
echo $this->data;
//decode data into an array
$decodedData = json_decode($this->data);
//standard saving code would
$this->Model->save($decodedData);
}
Stuck on the first stage of a big project. I am trying to display the JSON value that I get from URL shown below. It shows the data when I past the URL on the a browser. But when I put the URL in variable and try to show in html it doesn't show the phrased value.(I will delete the app/key one I get the solution.) Thanks in advance.
http://jsfiddle.net/rexonms/6Adbu/
http://api.flickr.com/services/rest/?format=json&method=flickr.photosets.getPhotos&photoset_id=72157629130565949&per_page=10&page=1&api_key=ccc93a20a1bb9060fa09041fa8e19fb5&jsoncallback=?
Have you tried using the $.getJSON() or the $.ajax() method? This seems to return the data just fine:
$.getJSON(apiCall, function(data) {
console.log(data);
});
Here's a working fiddle.
Additional Information
It seems like you may benefit from a simple tutorial that explains AJAX in relation to jQuery's $.getJSON() and $.ajax() methods.
$("<span>").html(apiCall)
apiCall is a string (containing the URL). All you're doing here is setting a span to have the URL as its content. You need to actually use AJAX to load said URL.
$.ajax({
url: 'http://api.flickr.com/services/rest/',
dataType: 'jsonp',
type: 'GET',
data: {
format: 'json',
method: 'flickr.photosets.getPhotos',
photoset_id: '72157629130565949',
per_page: 10,
page: 1,
api_key: 'ccc93a20a1bb9060fa09041fa8e19fb5'
},
jsonp: 'jsoncallback',
success: function(data){
console.log(data);
}
});
Inside success, data is the JSON object returned by the API.
i'm trying to send an js object to a php function using jquery.ajax.
This is what i have so far:
js side:
$.ajax({
type: "GET",
dataType: "json",
url: url,
data: {persoon : persoon2},
async: false,
success: function(){
alert(data);
return true;
}
});
php side:
$decode = json_decode($_GET["persoon"]);
$verzekering->setVoornaam($decode->persoon_voornaam);
in js this works: persoon2.persoon_voornaam
but i can't get to the value in php, what am i doing wrong?
few fixes
data: "persoon=persoon2", // check input format
success: function(data) { // missing data argument
EDIT your ajax code is working (check URL or php code)
http://jsfiddle.net/ish1301/KZndE/
Found the problem(s)
I was using this inside Drupal and the Jquery version was still 1.2.6. Upgrading it resolved a lot of the problems
The string i tried to catch with the $_GET["persoon"] was mall formated becaus i just send along a js object. Changing
data: {persoon : persoon2},
to
data: {persoon:JSON.stringify(persoon2)},
fixed the problem