I am working on a chat system which refreshes automatically using AJAX. First I was using the jQuery $.post function, but since i wanted to return JSON data from my PHP script, i want to use the $.ajax function. My script worked well using the $.post function, but i can not return JSON. This is the relevant code:
Javascript:
$.ajax({
url: "pages/loadmessage.php",
type: "POST",
data: {"c": getUrlParameter("c"), "t": messagetime},
dataType: "json",
success: function(pData){
console.log(pData);
},
error: function(xhr, status, error) {
alert(error + status);
}
});
PHP Code:
<?php
require_once("../init.php");
header('Content-Type: application/json');
if (Input::exists() && Input::get("c") && Input::get("t")) {
$chat = new Chat($user->data()->ID, Input::get("c"));
$messages = $chat->getNewMessages(Input::get("t"), $user->data()->ID);
if ($messages) {
$result = array(
'topic' => $chat->getTopic(),
'messages' => array()
);
foreach($messages as $m) {
array_push($result['messages'], array('source' => 'mine', 'Text' => $m->Text));
}
echo json_encode("string!!!");
}
} else {
echo json_encode("string" . Input::get("c") . Input::get("t") . Input::exists());
}
?>
I already tried to set the contentType of the AJAX call to "application/json" and convert the data to JSON using JSON.stringify, but then no input data gets to the PHP script. The code works if just one parameter (data: {"c": getUrlParameter("c")}) is sent to the PHP script...
I already searched StackOverflow, but i could not find a solution...
Thanks
JSON example:
Index.html
<script type="text/javascript">
$.ajax({
url: "out.php",
type: "POST",
data: {"param1": "test 1", "param2": "test2"},
dataType: "json",
success: function(data){
alert("param1:"+data.param1+" | param2:"+data.param2);
},
error: function(xhr, status, error) {
alert(error + status);
}
});
</script>
out.php
<?php
if(isset($_POST["param1"])){ $param1 = $_POST["param1"];}
if(isset($_POST["param2"])){ $param2 = $_POST["param2"];}
$out = array("param1"=>$param1,"param2"=>$param2);
echo(json_encode($out));
?>
Related
I have been trying to work this out for hours now and cannot find any answer that helps me.
This is the code in my javascript file
function sendMovement(cel) {
var name = "test";
$.ajax({
type: 'POST',
url: '../game.php',
data: { 'Name': name },
success: function(response) {
console.log("sent");
}
});
}
This is the code from my PHP file (it is outside the js file)
if($_SERVER["REQUEST_METHOD"] == "POST") {
$data = $_POST['Name'];
console_log($data);
}
When debugging I can see that AJAX is sending a POST and it does print in the console "SENT" but it does not print $data
update: the function console_log() exists in my PHP file and it works
Try getting response in JSON format, for that your js should have dataType:'JSON' as shown below
JS Code:-
function sendMovement(cel) {
var name = "test";
$.ajax({
type: 'POST',
dataType:'JSON', //added this it to expect data response in JSON format
url: '../game.php',
data: { 'Name': name },
success: function(response) {
//logging the name from response
console.log(response.Name);
}
});
}
and in the current server side code you are not echoing or returning anything, so nothing would display in ajax response anyways.
changes in php server code:-
if($_SERVER["REQUEST_METHOD"] == "POST") {
$response = array();
$response['Name'] = $_POST['Name'];
//sending the response in JSON format
echo json_encode($response);
}
I fixed it by doing the following:
To my game.php I added the following HTML code (for debugging purposes)
<p style = "color: white;" id="response"></p>
Also added in my game.php the following
if($_SERVER["REQUEST_METHOD"] == "POST") {
$gameID = $_POST['gameID'];
$coord = $_POST['coord'];
$player = $_POST['player'];
echo "gameID: " . $gameID . "\nCoord: " . $coord . "\nPlayer: " . $player;
}
AND in my custom.js I updated
function sendMovement(cel) {
var handle = document.getElementById('response');
var info = [gameID, cel.id, current_player];
$.ajax({
type: 'POST',
url: '../game.php',
data: {
gameID: info[0],
coord: info[1],
player: info[2]
},
success: function(data) {
handle.innerHTML = data;
},
error: function (jqXHR) {
handle.innerText = 'Error: ' + jqXHR.status;
}
});
}
i am passing my variable throught an AJAX request in javascript but not getting it in my php file. NOt sure where i am going wrong.?
JS code
var build = {
m_count : (document.getElementById('count').value),
}
$.ajax({
data: build,
type: "POST",
url: "tabs.php",});
PHP code
<?php
$module_c = $_POST['data'];
echo $module_c;
?>
You have to get the data by the name of the variable you want to get, which is m_count.
<?php
$module_c = $_POST['m_count'];
echo $module_c;
?>
EDIT:
Like suggested in the comments, change your JavaScript code to:
var build = {
m_count : (document.getElementById('count').value)
}
$.ajax({
data: build,
type: "POST",
url: "tabs.php",
success: function(data) {
alert(data);
}
});
PHP:
<?php
$module_c = $_POST['m_count'];
echo $module_c;
?>
JS:
var build = {
m_count : (document.getElementById('count').value),
}
$.ajax({
url: 'php/server.php',
type: 'POST',
data: build,
})
.done(function(msg) {
// JSON.parse turns a string of JSON text into a Javascript object.
var message = JSON.parse(msg);
alert(message);
}
})
.fail(function(err) {
console.log("Error: "+err);
})
.always(function() {
console.log("Complete");
})
;
Afternoon guys/gals,
I'm relatively new to using AJAX to POST information to a JSON file and I am not sure what the .php file should look like to process it. I have very little experience with .php. Am I on the right track? I've looked a lot of examples but most of them only have pieces of the .php file to process it. I am trying to inject the "task" into the JSON file which I then use handlebars to read on another page.
function fnCreateTask() {
var url = "save.php";
var title = $("#TaskTitle").val();
var date = $("#TaskDate").val();
var desc = $("#TaskDescription").val();
var info = {
Title: title,
Date: date,
Description: desc
};
var body = JSON.stringify(info);
$.ajax({
type: "POST",
url: url,
contentType: 'application/json',
data: body,
dataType: 'json',
error: function (err) {console.log(err)},
success: function (data) {
alert('Task Created.');
location.reload();
}
});
}
<?php
$fp = fopen('careers.json', 'w');
fwrite($fp, $_POST = json_decode(file_get_contents('php://input'), true););
fclose($fp);
?>
$.ajax POST (or GET for that matter) data will be x-form encoded by default when sent to the server. You can do
on the client
//object for the data
var data = {
title: $("#TaskTitle").val(),
date: $("#TaskDate").val()
};
$.ajax({
type: "POST",
url: "save.php",
data: data,
error: function (err) {console.log(err)},
success: function (data) {
alert('Task Created.');
location.reload();
}
});
and on the server
// as a separate object to be safe
$dataobj['title'] = $_POST['title'];
$dataobj['date'] = $_POST['date'];
// write json_encode object to file
file_put_contents ( 'filename.json' , json_encode($dataobj));
To create a JSON in PHP :
<?php
$array = array(
"name" => "toto",
"lastname" => "lafraise",
"age" => 33
);
$fp = fopen('careers.json', 'w');
fwrite($fp, json_encode($array));
fclose($fp);
I have an ajax call like so:
$.ajax({
url: '/assets/functions.php',
type: 'POST',
data: {
"functionCall": "get-uploads",
"type": type
},
dataType: 'json',
success: function (data, textStatus) {
console.log("done");
console.log(data);
console.log(textStatus);
},
error: function(textStatus, errorThrown) {
console.log("uh oh");
console.log(textStatus);
console.log(errorThrown);
}
});
Which gets sent to and handled with this:
switch($_POST['functionCall']) {
.
.
.
case "get-uploads":
$type = $_POST['type'];
$getUploads = "SELECT * FROM pp_uploads WHERE type = '$type';";
$docArray = array();
while($row = mysql_fetch_assoc($documents)) {
$docArray[] = $row;
}
echo json_encode($docsArray);
}
When I run this I get a parsing error, which from what I understand means that the returned data isn't being returned as JSON. So I changed the dataType to html, and I see that the returned data in the console is:
[{"id":"35","filename":"fdgsdf","path":"ConfiguratorTreeDiagram.pdf","type":"resources"},{"id":"36","filename":"gsrewg","path":"dhx_advertising.pdf","type":"resources"}]Array
(
[functionCall] => get-uploads
[type] => resources
)
So it looks like the data I passed into the call is being appended to the end of my data. How do I prevent that from happening?
It looks like you might be doing a print_r somewhere on an Array variable?
I'm trying to send a associative array via AJAX $.post to php. Here's my code:
var request = {
action: "add",
requestor: req_id,
...
}
var reqDetails = $("#request_details").val();
switch(reqDetails){
case 1:
request[note] = $("#note").val();
break;
...
}
if(oldRequest()){
request[previousID] = $("old_id").val();
}
$('#req_button').toggleClass('active');
$.post("scripts/add_request.php", {
request_arr: JSON.stringify(request)
}, function(data){
console.log(data);
$('#req_button').toggleClass('active');
}, 'json');
And i'm simply trying to read the received data in my php script:
echo json_decode($_POST["request_arr"]);
But it's not working. I'm a newbie to js, I can't figure out what I'm doing wrong.
Check below link for your reference
Sending an array to php from JavaScript/jQuery
Step 1
$.ajax({
type: "POST",
url: "parse_array.php",
data:{ array : JSON.stringify(array) },
dataType: "json",
success: function(data) {
alert(data.reply);
}
});
Step 2
You php file looks like this:
<?php
$array = json_decode($_POST['array']);
print_r($array); //for debugging purposes only
$response = array();
if(isset($array[$blah]))
$response['reply']="Success";
else
$response['reply']="Failure";
echo json_encode($response);
Step 3
The success function
success: function(data) {
console.log(data.reply);
alert(data.reply);
}
You are already using "json" as dataType, so you shouldn't apply 'stringify' operation on your data.
Instead of request_arr: JSON.stringify(request), can you try request_arr: request directly?