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?
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");
})
;
I have a simple search form which query an external server for result with jquery
$("#formsearch").on("submit", function (event) {
// everything looks good!
event.preventDefault();
submitFormSearch();
});
function submitFormSearch(){
// Initiate Variables With Form Content
var searchinput = $("#searchinput").val();
$.ajax({
type: "GET",
url: "https://external-server/api/",
headers: {"Authorization": "xxxxxxxxxxxxxx"},
data: "action=Search&query="+searchinput,
success:function(json){
console.log(json);
$.ajax({
type: "POST",
url:'search_func.php',
data: "func=parse&json="+json,
success:function(data) {
console.log(data);
$('#risultato_ricerca').html(data);
}
});
}
});
}
The first GET ajax works properly and I get correct data but trying to send this json data to my php script in post I can't get data.
This is the code in search_func.php
if(isset($_POST['func']) && !empty($_POST['func'])){
switch($_POST['func']){
case 'parse':
parse($_POST['json']);
break;
default:
break;
}
}
function parse($json) {
$obj = json_decode($json,true);
var_dump($obj);
}
... it displays NULL
Where I'm wrong ?
EDIT:
SOLVED
changing:
data: "func=parse&json="+json,
to:
data: { func: 'parse', json: JSON.stringify(json) },
json code is correctly passed to search_func.php
Changed function parse in php file to:
function parse($json) {
$data = json_decode(stripslashes($json),true);
print_r($data);
}
Thank you.
Is the javascript json variable correctly filled (i.e. what does your console show you?) Possible you must encode the json variable to a string before posting.
i.e: instead of data: "func=parse&json="+json, use data: "func=parse&json="+JSON.stringify(json),
See this: http://api.jquery.com/jquery.ajax/
The correct syntax is: data: { func: 'parse', json: my_json_here }
If this doesn't works is probably that you have to encode the JSON to a string (see JSON.stringify())
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));
?>
I created array like this ["9", "ques_5", "19", "ques_4"]. Now I want to send it from JS to PHP but I'm not getting proper results. My JS code is:
$(".button").click(function(e) {
e.preventDefault();
$.ajax({
type : 'post',
cache : false,
url : 'test/result.php',
data : {result : stuff},
success: function(resp) {
alert(resp);
}
});
});
In the above code stuff is an array which contains records. How can I send this array with above code and then in PHP I want to process this array like ques_5 is the key and 9 become the value for that key.
You can pass the data to the PHP script as a JSON object. Assume your JSON object is like:
var stuff ={'key1':'value1','key2':'value2'};
You can pass this object to the php code in two ways:
1. Pass the object as a string:
AJAX call:
$.ajax({
type : 'POST',
url : 'result.php',
data : {result:JSON.stringify(stuff)},
success : function(response) {
alert(response);
}
});
You can handle the data passed to the result.php as :
$data = $_POST["result"];
$data = json_decode("$data", true);
//just echo an item in the array
echo "key1 : ".$data["key1"];
2. Pass the object directly:
AJAX call:
$.ajax({
type : 'POST',
url : 'result.php',
data : stuff,
success : function(response) {
alert(response);
}
});
Handle the data directly in result.php from $_POST array as :
//just echo an item in the array
echo "key1 : ".$_POST["key1"];
Here I suggest the second method. But you should try both :-)
If you want to send key value pairs, which is what I am seeing, it would be better to use a PHP JSON library (like this one... http://php.net/manual/en/book.json.php)
Then you can send actual key value pairs, using JSON format like...
{"ques_5" : "19", "ques_4": "19"}
Try this
var array = ["9", "ques_5", "19", "ques_4"];
console.log(array.join(","));
above code will output string with comma separated like 9,ques_5,19,ques_4then paste it to ajax call.
And then in php explode that string.
Other possible solutions.
First
var obj = { 'item1': 'value1', 'item2': 'value2' };
$.ajax(
{
type: 'post',
cache: false ,
url: 'test/result.php',
data: { result : JSON.stringify(obj) },
success: function(resp)
{
alert(resp);
}
});
Second
var a = $.JSON.encode(obj);
$.ajax(
{
type: 'post',
cache: false ,
url: 'test/result.php',
data: { result : a },
success: function(resp)
{
alert(resp);
}
});
In PHP File
<?php
$json = $_POST["data"]
var_dump(json_decode($json));
?>
You can send the array in json format to the php and then use json_decode function to get back the array like
In ajax call you have to send json for that you need to first make array of the values so that you get it in right form
so that you json look like {"ques_5":"9","ques_4":19}
and use in ajax call
data: JSON.stringify(`your created json`),
contentType: "application/json; charset=utf-8",
dataType: "json",
IN PHP it look like
<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
?>
I would like to share a complete example that works for me in order to avoid making each JavaScript function for each PHP function
// on the HTML side a simple JavaScript call from a link
<a href="javascript:CargaZona('democonllamada', 'tituloprin', {'key1':'value1','key2':'value2'})" >test</a>
<div id='tituloprin' >php function response here!</div>
// on JavaScript side
function CargaZona(fc, div, params) {
var destino = "#" + div;
var request = $.ajax({
url : "inc/phpfunc.php",
type : "POST",
data : {
fc : fc,
params : JSON.stringify(params)
},
dataType : "html"
});
request.done(function (msg) {
$(destino).html(msg);
});
request.fail(function (jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
}
// on phpfunc.php page
<?php
$params = "{'key1':'value1','key2':'value2'}";
$fc = 'def';
if (isset($_POST['fc'])) { $fc = $_POST['fc']; }
if (isset($_POST['params'])) { $params = $_POST['params']; }
switch ($fc) {
default:
call_user_func($fc,$params);
}
function democonllamada($params) {
$params = json_decode("$params", true);
echo "ok llegaron".$params['key1'];
}
?>