Use AJAX/JSON to pass an array of objects to PHP - php

I need to pass a Javascript array of objects to PHP. Found about 3 solutions on the internet, but none of them worked for me. The array looks like this (in Chrome dev console):
And my current AJAX call looks like this:
function consolidate() {
var studentsstring = JSON.stringify(students);
$.ajax({
type: "POST",
url: "writefile.php",
dataType: "json",
data: {students: students},
success: function(data) {
alert(data);
}
});
}
And the PHP file looks like this:
<?php
print($_POST['students']);
?>
Currently, when I hit the "consolidate" button, nothing happens. No alert is shown. Chrome dev reports no errors in the code.

Oh, I'm dumb. Too many hours of coding. The line should have been:
data: {students: studentsstring},
and now it works. Thanks all.

Related

jQuery POST not working - seems it should be

It's been a while since I've played with jQuery, so I'm wondering what I'm missing here.
I've set up a php page that writes a test txt file when the jQuery calls it.
The txt file is being written, so jQuery is finding the php page, but then displays my error alert, not my success one, so something is not working.
My php:
$testfile=$_SERVER["DOCUMENT_ROOT"].'/test.txt';
$file5 = fopen ($testfile, "w");
fwrite($file5, 'testy');
fclose ($file5);
exit();
My jQuery:
var g = {
r: 1
};
$.ajax({
type: "POST",
url: "/test.php",
cache: false,
data: g,
success: function (data) {
alert('yay');
},
error: function (data) {
alert('nay');
}
});
Anything obvious I'm missing?
Thanks for taking a look.
I think the problem is on the url you are requesting. Its hard to tell without know the type of error or without knowing your folder structure or if you are using any PHP framework. Please, write details
Try this--
url: "test.php",

ajax always going to error

Im trying to learn to use ajax at the moment, but unfortunately I cannot get it to success.
$('.engineering-services').live('click', function() {
$.ajax({
url: 'index.php?route=information/information/homepage_info',
type: 'post',
data: {info_description : 'test'},
dataType: 'json',
success: function(json){
alert('pass');
},
error: function(json) {
alert('fail');
}
});
});
Here is the php function...
public function homepage_info() {
$json = array();
if (isset($this->request->post['info_description'])) {
echo $this->request->post['info_description'];
echo '<br /> test2';
}
$this->response->setOutput(json_encode($json));
}
However this always makes a fail alert instead of a pass one.
Am I missing something obvious here?
EDIT: Its finding the function ok, as in the console it is giving the correct response,
i.e.
test
test2
Thank you
If your dataType is set to json, anything returned that is not JSON will cause the ajax call to error out. Try sending some json back to the script... {"test":"abc"} or similar. I see a couple of calls to echo in your code, for example.
Not just this, but any PHP error/warning/notice printed to the browser will break calls.
Hint: you can generate valid JSON from PHP variables using json_encode().
You cannot combine an existing query string with data. Something like this should work (or at least be syntactically valid):
$.ajax({
url: 'index.php',
type: 'post',
data: {information:'information/information/homepage_info',info_description:'test'},
dataType: 'json',
success:function(json){
alert('pass');
},
error:function(json) {
alert('fail');
}
});
Also as was mentioned, anything that is not json will potentially cause an error, so you not echo those html components ... if anything, you print them.
Also, as a side note your dataType should be done server side with a header('Content-type: application/json'); declaration in index.php rather than in your jQuery script. Its guaranteed to be recognized as json that way, and also less Javascript code.

Cannot receive echo from PHP file via jQuery and AJAX

I want to begin by saying sorry for asking this question because I know this has been asked a lot on here already. I've search through the site and used Google, and looked at other examples but I can't figure out what's wrong. Running the script with FireBug running shows the POST is sent but nothing gets received. I've posted the code below.
Jquery Code:
$('#studio').submit(function (event) {
$('#formLaunch').click();
$.ajax({
url: 'test.php',
type: 'POST',
data: {
search_var: 'test'
},
dataType: 'html',
success: function (data) {
//$('#result').html(data);
alert(data);
}
});
event.preventDefault();
});
PHP Code:
<?php
$term = $_POST['search_var'];
echo $term;
?>
The end result of the code (once the AJAX request starts working) will process sent variables and echo an image which I want displayed in a DIV box on the page. For starters though just trying to get this basic 'shell' to work properly.
Thanks in advance for any help or direction.
Jeff
Always provide an error function, especially when in development. I suspect you have an error for a response (404, 500, etc). Providing an error function for debugging purposes will help you see this more quickly.
try this
$.post('test.php',{'search_var': 'test'},function(data){
alert(data);
});

JQuery Mobile POST data empty in $_POST

I'm running into a problem with JQuery Mobile (new to me) and the AJAX-call. I'm using the following code:
$.ajax({
type: "POST",
url: "http://**correct url**/post/todoitem",
beforeSend: addHeaders,
dataType: "json",
contentType: "application/json",
data: { "todoitem":"test" }, // this is just as a test
success: function(result) {
alert("Success: " + JSON.stringify(result));
},
error: function() {
alert("Error: " + JSON.stringify(arguments));
}
});
While executing this, it calls a PHP script where I need the data from the todoitem, so in this case the string "text" (in the end, multiple variables are to be send, but for now I'm just using one parameter for simplicity).
My PHP code looks like this (also just for testing purposes):
echo json_encode($_POST));
The result is: nothing, null. The $_POST seems to be empty. I've searched and tried many things, but most answers (even here on stackoverflow) are about forms and people say I need to serialize the contents of the form. However, I'm not using a form at all.
I also tried
data: JSON.stringify({ "todoitem" : "test" })
as some suggested but this did not work either.
I do know that the data is being transfered because of this little PHP hack I tried:
echo file_get_contents('php://input');
That exactly shows the data: todoitem = test. So where does this all go wrong? I'm working on this for days now! Thnx in advance
The problem is with this part of your code:
contentType: "application/json",`
Removing that line should make the sent Content-Type header default to application/x-www-form-urlencoded and PHP will decode the request into $_POST.

PHP and Jquery's json

My html file:
<script>
$(document).ready(function() {
$.ajax({
type: "POST",
url: "search.php",
data: "id=1",
datatype: "json",
success: function(msg){
$('.result1').html(msg["name"]);
}
});
})
</script>
<span class="result1"></span>
My php file:
<?
$a["name"] = 'john';
echo json_encode($a);
?>
Why the name John doesn't appear in class result1? Why? Please help me, I am going insane.
edit: Is it possible to make bounty right now?
The dataType parameter has a capital T. It works if you correct this.
Currently it is (by default) trying to guess the response format based on the mime-type, so probably defaulting to html - debugging in firebug you can see that the msg argument of the success callback is a string containing the JSON.
Not to distract you from solving this problem. But you may want to look into the .getJSON() function http://api.jquery.com/jQuery.getJSON/. It's a little cleaner if you're just getting some data.
Also, take a look at the JSON format, I think data: "id=1" should be data: "{id:1}"
And on the response side, keep in mind it's expecting multiple records so try: msg[0].name;, check out the each() function to process multiple records.
I think you should use:
$('.result1').html(msg.name);

Categories