I have two files, game.js and gallery.php. So I have been trying to send an array from game.js to gallery.php through ajax. I have attached the code I tried , below:
game.js:
imgarray.push({"img_name":img_name,"x":x_value,"y":y_value,"w":w_value,"h":h_value});
var st = JSON.stringify(imgarray);
$.ajax({
url: "gallery.php",
method: "POST",
data: { data :st},
success: function(data){
console.log(st);
alert("OK");
}
});
gallery.php:
<?php
$data = json_decode(stripslashes($_POST['data']));
foreach($data as $d){
echo $d;
}?>
so in the above code , when I run it , in the console log for game.js i am able to print the array. but when I tried to get the array in gallery.php and print it, it throws an error, says st_img is undefined and the for the echo it produces NULL.
Can someone help me fix this.
Related
I want to call a remote php script and that php script will echo any string and then I want to alert that string back to ajax. but when I am alerting that string, I am getting this
Following is my ajax code:
$(document).ready(function(){
var response= $.ajax({
type:"POST",
dataType:'text',
url:"http://mySiteURL.com/evote.php?checkVote="+voterId+"&fingerPrint="+fingerPrint,
async:true,
success:function(result){alert(result);},
error: function(result){alert(result);}
});
});
and following is my php script code
<?php
if(isset($_POST['checkVote'])){
$voterId=$_POST['checkVote'];
$fingerPrint=$_POST['fingerPrint'];
echo "Output from php";
}
?>
before this I searched many questions on stack overflow but problem persisted.
Change the reponse into string : JSON.stringify(result)
var response= $.ajax(
{
type:"POST",
dataType:'html', // <-----
url:"http://mySiteURL.com/evote.php?checkVote="+voterId+"&fingerPrint="+fingerPrint ,
// async:true, // <--- no need
success:function(result){alert(JSON.stringify(result));},
error: function(result){alert(JSON.stringify(result));} })
For the PHP
<?php
if(isset($_GET['checkVote'])){
$voterId=$_GET['checkVote'];
$fingerPrint=$_GET['fingerPrint'];
echo "Output from php";
} else {
echo "No POST";
}
?>
I got this Ajax code on Js/Jq block (/buscador/menuLateral/menu-libros.php):
$.ajax({
url: '<?= get_stylesheet_directory_uri(); ?>' +
'/buscador/buscador-functions.php',
type: 'POST',
data: {
sendCheckedVal: 'yes',
tipo: 'editorial',
valor: valor_recogido,
archivo: this_file_id.toString()
},
success: function(data) {
alert('Checked value !');
}
});
Values on this file exists and got some value, I tried seeing it with a GET on a Stringify.
And this, must be getted in a file like this (/buscador/buscador-functions.php) :
<?php
if (ISSET($_POST['sendCheckedVal'])){
echo 'hi, u reached here' ;
}
?>
The values doesn't passes from js code file to next.
I get this error on console:
POST
[WP-URL-HIDDEN-ON-PURPOSE]/themes/ChildrenNewspaper/buscador/buscador-functions.php
500 (Internal Server Error)
On right side of the line-error :
jquery.min.js:2
Someone knows how to repair this on ajax working on a wordpress theme.Thanks
Issue is here : alert('hi, u reached here');. alert() is not PHP function it is javascript function. So instead of it you can use echoor return
<?php
if (isset($_POST['sendCheckedVal'])){
echo 'hi, u reached here';
}
?>
To start you off, alert is a javascript function.
In php you need to echo out values to the page;
If you want to do it with JS you need to print out js.
echo "<script type='text/javascript'>alert('hi, u reached here');</script>";
Or you can echo out the vars to the page.
I have currently a problem with my code. I would like to send JSON data with Ajax to a PHP script but it doesn't work. What does work is that the PHP script can be called by the Ajax code but it can't put the code into the .txt file. I have tried several things but I can't get it working. (I am trying to set the users array in the .txt file)
jQuery code:
var users = [];
$.ajax({
type: "POST",
url: hostURL + "sendto.php",
dataType: 'json',
data: { json: JSON.stringify(users) },
success: function (data) {
alert(data);
}
});
PHP Code:
<?php
$json = $_POST['json'];
$data = json_decode($json);
$file = fopen('test.txt','w+');
fwrite($file, $data);
fclose($file);
echo 'Success?';
?>
You must know that in PHP json_decode generates an Array that you can't write into an text file.
So only remove the json_decode command.
Since json_decode() function returns an array, you can use file_put_contents() that will save each array element on its own line
<?php
$json = $_POST['json'];
$data = json_decode($json, true);
file_put_contents('test.txt',implode("\n", $data));
?>
I have a form with 17 checkboxes. When one of these changes, JavaScript should submit the values to the server (running PHP).
I want to use JSON, because the checkboxes give two arrays which have to be seperated in PHP
In JS, I create an JSON-String, which I want to submit via POST and read and decode in PHP.
The String looks like this atm: [["2015-06-26","2015-06-27"],["2","3","4","5","6","7","8","9","10","11","12","13","14"]] - This is what I want it to be.
This is, what my AJAX-function looks like:
var fullArray = [dateArray, trackArray];
var jsonFullString = JSON.stringify(fullArray);
//jsonFullString == [["a","b","c"],["d","e","f","g"]]
$.ajax({
type:'POST',
url:'shownitems.php',
data: jsonFullString,
success: function(data){
//More script. This comment is reached, because
alert(data);
// works.
}
});
When I get it to PHP, and search for $_POST[0] the success function in JS doesn't show anything. When I search for $_POST, I get "Array.." back.
This is, what my PHP looks like (This is my test snippet):
<?php
echo $_POST;
echo ".";
echo $_POST[0];
echo ".";
echo $_POST[0][0];
$array = array();
?>
I am also using jQuery.
In your JS:
/* dateArray and trackArray must be variables with values */
$.ajax({
method: "POST",
url: "shownitems.php",
data: { date: dateArray, track: trackArray }
}).done(function(response) {
alert(response);
});
In your PHP:
<?php
var_dump('Date: '.$_POST['date']);
var_dump('Track: '.$_POST['track']);
?>
You should get your request content instead the $_POST variables.
Something like this would
$json = file_get_contents('php://input');
$obj = json_decode($json); //Will contain your array of two arrays
In case you wanted to get your post variables like you are doing, you could change your AJAX request and use:
$.ajax({
type:'POST',
url:'shownitems.php',
data: {
data: jsonFullString
},
success: function(data){
//More script. This comment is reached, because
alert(data);
// works.
}
});
And your PHP would be:
$json = $_POST["data"];
$obj = json_decode($json); //Will contain your array of two arrays
I have an array that i pass from javascript to php and in php page i am trying to put it in session to be used in the third page. The code is as below
JavaScript:
var table_row = [];
table_row[0] = [123,123,123];
table_row[1] = [124,124,124];
table_row[2] = [125,125,125];
var jsonString = JSON.stringify(table_row);
$.ajax({
type: "POST",
url: "test1.php",
dataType: "json",
data: {myJSArray: jsonString},
success: function(data) {
alert("It is Successfull");
}
});
test1.php
<?php
session_start();
$check1 = $_POST['myJSArray'];
$_SESSION['array']= $check1;
echo $check1;
?>
test2.php
<?php
session_start();
$test = $_SESSION['array'];
echo $test;
?>
on submit i call the function in javascript and the form takes me to test2.php. It is giving error on test2.php page Notice: Undefined index: array in C:\xampp\htdocs\test\test2.php on line 13
Any suggestions please do let me know.
You don't need to stringify yourself, jquery does it for you, if you stringify it, jQuery will believe you want a string instead
var table_row = [];
table_row[0] = [123,123,123];
table_row[1] = [124,124,124];
table_row[2] = [125,125,125];
$.ajax({
type: "POST",
url: "test1.php",
dataType: "json",
data: {myJSArray: table_row},
success: function(data) {
alert("It is Successfull");
}
});
However, on the php side, you still need to decode it as it is always a string when you get it from $_POST. use json_decode to do it.
$check1 = json_decode($_POST['myJSArray']);
look at your test2.php
<?php
session_start();
$test = $_SESSION['array'];
echo $test;
?>
if it's only the code in the file then the error you got C:\xampp\htdocs\test\test2.php on line 13 is mindless, because there is not line 13,
but if you have something about the code you show us, may there be something echoed before?
because session has to be started before any output,
otherwise I've tested whole script and works fine...
To check if session really started (otherwise $_SESSION will not work), try this:
if(session_id())
{
echo "Good, started";
}
else
{
echo "Magic! strangeness";
}
if problem not found in test2.php you can check test1.php echo $_SESSION['array'] after saving it, and in your javascript callback function alert data param itself,
I'm sure you can catch the problem by this way.
i got it to work, the code is below
Javascript file: in page index.php
Either you can call this function and pass parameter or use code directly
var table_row = []; //globally declared array
var table_row[0]=["123","123","123"];
var table_row[1]=["124","124","124"];
var table_row[2]=["125","125","125"];
function ajaxCode(){
var jsonArray = JSON.stringify(table_row)
$.ajax
({
url: "test1.php",
type: "POST",
dataType: 'json',
data: {source1 : jsonArray},
cache: false,
success: function (data)
{
alert("it is successfull")
}
});
}
Page: test1.php
session_start();
unset($_SESSION['array']);
$check1 = $_POST['source1'];
$_SESSION['array']= $check1;
echo json_encode(check1);
Page: test2.php //final page where i wanted value from session
if(session_id())
{
echo "Session started<br>";
$test = $_SESSION['array'];
echo "The session is".$test;
}
else
{
echo "Did not get session";
}
?>
In index page i have a form that is submitted and on submission it calls the ajax function.
Thank you for the help, really appreciate it.