I know there a fair few entries on SO and the web on this however I just can't get to work - any help would be appreciated.
So i have an array in Javascript which I'm trying to pass on to PHP.
I've got a little JS function to first POST it, so:
function sendToPHP() {
$.post("index.php", { "variable": toSearchArray });
}
Then down the page, I have the PHP:
<?php
$myval = $_POST['variable'];
print_r ($myval);
?>
*The prints just there for me to check.
Any ideas - fyi I'm using MAMP so its localhost:8888/index.php. Could this be causing issues in that the URL is not correct?
Thanks.
You have a misunderstanding about how ajax works. Although jquery makes it easy, it is still not automatic. You should just find a tutorial about ajax with jquery, but if you want to just send an array to php and see the output on screen, something like this would work:
index.php
<html>
<head>
<title>Test</title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
//attach to the button a click event
$('#btn').click(function(){
//get the value from the textbox
var txt=$('#txt').val();
//if txt is blank, alert an error
if(txt == ''){
alert("Enter some text");
} else {
//send txt to the server
//notice the function at the end. this gets called after the data has been sent
$.post('catcher.php', {'text':txt}, function(data){
//now data is an object, so put the message in the div
$('#response').text(data.message);
}, 'json');
}
});
});
</script>
</head>
<body>
<input type="text" id="txt">
<input type="button" id="btn">
<pre id="response" style="overflow:auto;width:800px;height:600px;margin:0 auto;border:1px solid black;"> </pre>
</body>
</html>
catcher.php:
<?php
//if something was posted
if(!empty($_POST)){
//start an output var
$output = array();
//do any processing here.
$output['message'] = "Success!";
//send the output back to the client
echo json_encode($output);
}
It is better to use 2 files, one for the user to load that initiates the ajax call and one page to handle the ajax call. Sending an array works the same, just replace getting the textbox value with sending an array.
Instead of declaring variable toSearchArray as array. consider it an javascript object.
var toSearchArray = {}.
This is what happens when you open your page (index.php)
A GET request is issued to index.php and the content is returned. There are no values in the $_POST array so your print_r() line does nothing.
Javascript is executed that sends a POST request to index.php via AJAX. Note that this is an entirely new request, separate to the original GET. The $_POST array will be populated on this request however the response is discarded.
Hopefully this will illustrate what you can do.
ajax.php
<?php
header("content-type: application/json");
exit(json_encode($_POST));
index.php
<script>
const toSearchArray = ['some', 'array', 'with', 'values'];
$.post('ajax.php', {
variable: toSearchArray
}).done(data => {
console.log(data) // here you will see the result of the ajax.php script
})
</script>
Well I don't think thats the right way to do it when it comes to arrays, see you need to use JSON encode in javascript then JSON decode in php
Refer to this question Pass Javascript Array -> PHP
Related
I'm trying to create a like button for different images posted by user. This is my html :
Like
This is my javascript:
<script>
$(function(){
$(".likes").click(function(){
var postid = $(this).attr("id");
alert(postid);
$.ajax({
type:'POST',
url:'likes.php',
data:'id='+postid,
success:function(data){
alert("success");
}
});
});
});
</script>
This is likes.php, for testing purpose it's quite simple:
<?php
require('config.php');
$postid=$_POST['id'];
echo $postid;
?>
When I clicked the like button, a small window will correctly postid, and then "success",which indicates that the ajax is successful, however, when I opened likes.php, I got an error that says: Notice: Undefined index: id in C:\XAMPP\htdocs\likes.php on line 3
I tried adding e.preventDefault(). I tried different syntax,such as data:'id='+postid, data:{id:postid},data:{'id':postid},etc. I experimented with basically all combinations of single quotes and double quotes. I also tried adding datatype:html and datatype:text. Every time I just got a alert that says "success", but when I open likes.php, $_POST['id'] is always undefined.
Can someone help me please this bug took me a lot of time.
Update: I found that even if I entered a completely non-existing url, like url:"aabbll.php", after I clicked the "like" button, I would still see a window that alerts "success", why does the page keep alerting "success" even though clearly the AJAX process wasn't a success?
You are not sending the post variable "id" when you are opening like.php in a new browser window.
The error "Notice: Undefined index" is shown because the $_POST array does not contain the id field.
You can use a chrome extension called postman to test endpoints with post variables.
A tip to improve the code could be to wrap it in an if isset statement
if(isset($_POST['id'])){
// this code will only be executed if the post variable is sent to the page
$postid=$_POST['id'];
// update database
echo "Success";
}else{
echo "ERROR: No id post variable found";
}
Your javascript code is sending the post variable
Try to put var_dump($_POST) to see what you really post.
Couple of suggestions.
Your JS can be simply
<script>
$(function() {
$('.likes').on('click', function() {
var postid = $(this).attr('id');
$.post("likes.php", {id: postid}).done(function( data ) {
alert( 'Data Loaded: ' + data );
});
});
});
For your PHP
<?php
if (!isset($_POST['id'])) {
/// Do what you want to do in this case.
}
$id = $_POST['id'];
// If using PHP7
$id = $_POST['id'] ?? null;
Though $('.likes') works try to avoid that since it is slowest selector in most cases.
This question already has answers here:
How do I pass JavaScript variables to PHP?
(16 answers)
Closed 2 years ago.
How do I pass have a Javascript script request a PHP page and pass data to it? How do I then have the PHP script pass data back to the Javascript script?
client.js:
data = {tohex: 4919, sum: [1, 3, 5]};
// how would this script pass data to server.php and access the response?
server.php:
$tohex = ... ; // How would this be set to data.tohex?
$sum = ...; // How would this be set to data.sum?
// How would this be sent to client.js?
array(base_convert($tohex, 16), array_sum($sum))
Passing data from PHP is easy, you can generate JavaScript with it. The other way is a bit harder - you have to invoke the PHP script by a Javascript request.
An example (using traditional event registration model for simplicity):
<!-- headers etc. omitted -->
<script>
function callPHP(params) {
var httpc = new XMLHttpRequest(); // simplified for clarity
var url = "get_data.php";
httpc.open("POST", url, true); // sending as POST
httpc.onreadystatechange = function() { //Call a function when the state changes.
if(httpc.readyState == 4 && httpc.status == 200) { // complete and no errors
alert(httpc.responseText); // some processing here, or whatever you want to do with the response
}
};
httpc.send(params);
}
</script>
call PHP script
<!-- rest of document omitted -->
Whatever get_data.php produces, that will appear in httpc.responseText. Error handling, event registration and cross-browser XMLHttpRequest compatibility are left as simple exercises to the reader ;)
See also Mozilla's documentation for further examples
I run into a similar issue the other day. Say, I want to pass data from client side to server and write the data into a log file. Here is my solution:
My simple client side code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
<title>Test Page</title>
<script>
function passVal(){
var data = {
fn: "filename",
str: "this_is_a_dummy_test_string"
};
$.post("test.php", data);
}
passVal();
</script>
</head>
<body>
</body>
</html>
And php code on server side:
<?php
$fn = $_POST['fn'];
$str = $_POST['str'];
$file = fopen("/opt/lampp/htdocs/passVal/".$fn.".record","w");
echo fwrite($file,$str);
fclose($file);
?>
Hope this works for you and future readers!
I'd use JSON as the format and Ajax (really XMLHttpRequest) as the client->server mechanism.
Using cookies is a easy way. You can use jquery and a pluging as jquery.cookie or create your own.
Using Jquery + jquery.cookie, by example
<script>
var php_value = '<?php echo $php_variable; ?>';
var infobar_active = $.cookie('php_value');
var infobar_alert = any_process(infobar_active);
//set a cookie to readit via php
$.cookie('infobar_alerta', infobar_alerta );
</script>
<?php
var js_value = code to read a cookie
?>
I've found this usefull Server-Side and Hybrid Frameworks:
http://www.phplivex.com/
http://www.ashleyit.com/rs/
I've been using Ashley's RSJS Script to update values in HTML without any problem for a long time until I met JQuery (ajax, load, etc.)
There's a few ways, the most prominent being getting form data, or getting the query string. Here's one method using JavaScript. When you click on a link it will call the _vals('mytarget', 'theval') which will submit the form data. When your page posts back you can check if this form data has been set and then retrieve it from the form values.
<script language="javascript" type="text/javascript">
function _vals(target, value){
form1.all("target").value=target;
form1.all("value").value=value;
form1.submit();
}
</script>
Alternatively you can get it via the query string. PHP has your _GET and _SET global functions to achieve this making it much easier.
I'm sure there's probably more methods which are better, but these are just a few that spring to mind.
EDIT: Building on this from what others have said using the above method you would have an anchor tag like
<a onclick="_vals('name', 'val')" href="#">My Link</a>
And then in your PHP you can get form data using
$val = $_POST['value'];
So when you click on the link which uses JavaScript it will post form data and when the page posts back from this click you can then retrieve it from the PHP.
You can pass data from PHP to javascript but the only way to get data from javascript to PHP is via AJAX.
The reason for that is you can build a valid javascript through PHP but to get data to PHP you will need to get PHP running again, and since PHP only runs to process the output, you will need a page reload or an asynchronous query.
the other way to exchange data from php to javascript or vice versa is by using cookies, you can save cookies in php and read by your javascript, for this you don't have to use forms or ajax
This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
There have been far too many questions on this subject but I still fail to understand.
Case:
Hyperlinked image
OnClick of image: Check if session exists
If session exist, open link
If session does not exist, show login form
onclick is calling a JavaScript function:
var my_global_link = '';
var check = '<?php echo $_SESSION["logged_in"]; ?>';
function show_login( link ) {
if(check == 1)
{
window.location = link;
}
else
{
my_global_link = link;
// .. then show login modal that uses 'js/whitepaper-login.js'
document.getElementById('light').style.display='block';
document.getElementById('fade').style.display='block';
document.getElementById('fade').scrollIntoView(true);
}
}
Global variable is being saved in another php file as :
$_SESSION['logged_in'] = 1;
I am unable to capture the session value in the var check. Can you advise?
Using jQuery here is a simple example of how to get a PHP $_SESSION into your JavaScript:
session.php
<?php
session_start();
$_SESSION['foo'] = 'foo';
echo $_SESSION['foo']; // this will be echoed when the AJAX request comes in
?>
get_session.html (assumes jQuery has been included)
<script>
$(function() {
$('a').click(function(event){ // use instead of onclick()
event.preventDefault(); // prevents the default click action
// we don't need complex AJAX because we're just getting some data
$.get('session.php', function(sessionData) {
console.log( sessionData ); // session data will be 'foo'
});
});
});
</script>
click
If this is successful you'll see the data and can use it in other JavaScript functions by passing the data appropriately. I often find it handy to json_encode() session data, returning JSON to be used by JavaScript, but there is no need to in a simple example such as this one.
Make the request to someone file.php
$( document ).ready(function(){//run when DOM is loaded
$.post("file.php", //make request method POST to file.php
function(data){ //callback of request is data
var arr = jQuery.parseJSON(data); //make json decoding
if(arr.logged == 1) //arr.logged is value needs
#do
})
})
file.php
<?php
session_start(); //start session for my dear friend Jay Blanchard
$_SESSION['logged_id'] = 1; //init value for example
$array = array('logged' => $_SESSION['logged_id']);//creat array for encoding
echo json_encode($array); //make json encoding for call back
?>
your javascript is not a very good solution, as it can be hacked easily. One can simply change the value of check to whatever one likes, and even without a login one would be able to access the link of the picture.
A better implementation would probably be something like:
<img src="img.png" alt="" />
checklogin.php would then verify the $_SESSION variable. If validated, you can use header("Location: something.html"); to redirect to where you want to bring the user. If not logged in, you can instead redirect to the login page: header("Location: login.php");
#Sarah
You have to first call the php file via ajax and set the javascript variable as the result. Since the javascript is a client side scripting language hence it can't read server side PHP script.
Hence on click call javascript function
function someFunc(){
//Fire Ajax request
//Set check variable
//and perform the function you want to ...
}
<?php include "sess.php"; ?>
<script type="text/javascript">
var my_global_link = 'testr.com';
var check = '<?php echo $_SESSION["logged_in"]; ?>';
function show_login( link ) {
if(check == 1)
{
window.location = link;
}
else
{
my_global_link = link;
document.getElementById('light').style.display='block';
document.getElementById('fade').style.display='block';
document.getElementById('fade').scrollIntoView(true);
}
}
</script>
<a href="#" onclick="show_login('test')" >test</a>
file1.php
<?php
session_start();
$_SESSION["logged_in"] = 1;
?>
sess.php
I have done this using two files. You may have not included session file I guess. Its working fine for me.
I have script like this
function getval(sel) {
var id= sel.value;
$.ajax({
type:"POST",
url:"./tab.php",
data:{id:id,task:'search'},
success: function(response){
//(I don't know what i should write for pass to php code)
}
});
}
I don't know how I can pass data response to php code ?
For Example: if I alert response, it's show 123 .so I want pass value 123 to a variable in php
$id = 123
response is the result passed BY php, not TO php. What's passed to php is the id and the task.
In your tab.php, you can access these two values :
<?php
$id = $_POST['id'];
$task = $_POST['task'];
//do anything you want with it...
?>
This is not the right workflow. PHP executes on runtime, so every time the page has finished loading you can't really put variables back into PHP (unless you reload the page). This is where AJAX comes in, so you can call PHP scripts from JavaScript / jQuery and don't have to reload the page every time.
The right thing to do is to either store the variable you have generated in the tab.php script in a database, $_SESSION, $_COOKIE or something similar like so:
//put this at the top of all your php scripts you want to use the variable in
session_start();
//now store the variable you wanted to pass (in tab.php)
$_SESSION['returnValue'] = $myValue;
Now if you want to use the variable in other pages just echo it like so (remember to add session_start() at the top of the PHP script.
echo $_SESSION['returnValue'];
First of all, start by reading this
To answer your question,
function getval(sel) {
var id= sel.value;
$.ajax({
type:"POST",
url:"./tab.php",
data:{id:id,task:'search'},
success: function(response){
//(I don't know what i should write for pass to php code)
}
});
}
The result from id and task are sent via $_POST (type:"POST") to the page tab.php (url:"./tab.php"). If you want to do that on a different page, just change the url in your ajax call: url:"./any_other_page.php" and the posted values will be sent there
Finally, read THIS post as well. It is greatly written and very well explained.
Hope it helps!
Keep on coding!
Ares.
On Page1:
An AJAX script is processed loading Page2
On Page2:
A mysqli Database query will run, if the database query is successful, I want to send a success response back to AJAX query and reload the page. If the database query fails, I want to send a fail response back to AJAX query and redirect to fail page.
Is this possible? How would I write this? I'm new to AJAX and have reviewed some AJAX scripts and also read documentation, but I learn best by experimenting with code to find solutions that work for me. I have played with a few ajax scripts but can't get any of them to work correctly and can't find one that does anything near what I need. Seems like it would be a fairly easy ajax script, so I was hoping someone could help me with it.
Here's a possible jQuery solution. Let me know if you want pure JavaScript.
index.html
<input type="text" id="input" />
<button type="button">Submit!</button>
scripts.js
$('button').on('click',function() {
var val = $('#input').val();
sendQuery(val);
});
function sendQuery(x) {
var val = x;
$('body').load('query.php?input=' + val);
}
query.php
$mysqli = new mysqli('localhost','root','password','db');
$val = $_GET['input'];
$query = <<<Q
SELECT
*
FROM
table
WHERE
column = ?
Q;
$stmt = $mysqli->stmt_init();
if($stmt->prepare($query)) {
$stmt->bind_param("i",$val);
$stmt->execute();
while($stmt->fetch()) {
#if the query is successful
echo '<script>
$(function() {
location.reload();
});
</script>';
}
} else {
echo '<script>
$(function() {
window.location.href = "http://www.yoursite.com/errorpage.html";
});
</script>';
}
$mysqli->close();
The only thing I'm uncertain about is why you want to send a response back with AJAX, and then move to a completely new page. To me that kind of seems like that negates the reason you're wanting to use AJAX in the first place. Any thoughts?
What the above does is use jQuery to load XMLHTTPRequest.responseText into the body (the reponseText is the scripts that are echoed by your php doc). In this case, in the case of success from the db, it echoes a script that reloads the page. In the case of a failure, it echoes a script that moves the user to an error page.