I have some code
<script>
FB.Event.subscribe('auth.login', function(response)
{
FB.api('/me', function(response) {
alert(response.id);
});
</script>
An alert screen appears and shows the value i want (response id). but i would like to assign this value to a php value called $id i know how to do this but because the value is in script it wont work, i have tried adding in the below code without success
</script> <?php $id ?> <script> response.id </script> <?php ; ?> <script>
this code is added just below the alert(response.id);
If you want to use the value on the server side the only way is to send it with AJAX to the server and after that store it in the Database or do something.
You can do something like this
<script>
FB.Event.subscribe('auth.login', function(response)
{
FB.api('/me', function(response) {
$.ajax({ type: "POST", url: "save-fb-id.php",data: {id: response.id} });
}
});
</script>
Forgot to mention this is jQuery implementation
In your PHP script do the following:
<?php
$fbID = $_POST['id'];
save_to_db($fbID);
?>
PHP code is executed by the server before it sends the page to the client. Anything in a script tag is executed by the client. In order to send a value back to PHP, you'll have to submit some kind of request back to the server - it could be a hyperlink (a href='page.php?id=whatever), a form with a hidden value, an ajax request, etc
To add the value to a database, you'll need a php page (eg mypage.php) to insert your entry, with something like
if (isset($_GET['insertme'])) {
mysql_query("INSERT INTO myidtable (id) VALUES ('{$_GET['insertme']}')");
}
And in your script, find some kind of ajax function and send a request to mypage.php?insertme=myid, where mypage is your database inserting page and myid is the id you want to insert.
Note that it's unsafe to insert values from $_GET directly into your database like that - you'll want to filter out single quotes first to prevent sql injection.
Related
I'm new to PHP and trying to figure this out and still not understanding. I'm trying to take the value of a html text box in jQuery and turn it into a variable I can then store as a (variable or string?) and pull back again after a page refresh.
I want the user to hit a button that then executes the following:
$('.save').click(function () {
// pulls the value from the textarea
var file = $('#subtext').val();
// send to php to hold text
$.ajax({
url: '/mininote/system/data.php',
type: 'POST',
data: { textbox: file },
success: function(data) {
alert('Saved data to php!');
$(save).text('All changes saved.').show().delay(3000).fadeOut(800);
}
});
});
Then receives the post data and stores in the php until the user reloads the page where it pulls data (or checks if there is any) from the php like so and replaces the value of the textbox with the value from the php:
$.ajax({
url: '/mininote/system/data.php',
type: 'GET',
data: { textbox: file },
success: function(data) {
// add text back to text box
$("#subtext").val(data);
}
});
Basically what I'm looking for is below:-
a way to perform an ajax POST to insert the data grabbed from the textbox,
add to PHP
on a page reload use a GET request and replace textbox text with text from the PHP file.
What would I need to put into the PHP code? Or would it be easier to go in another direction? I've gotten this method to work in local storage. I also want browser compatibility for this work.
I don't need to set it up for a bunch of users. Any response that will increase my knowledge on this will help greatly.
EDIT: I'm really looking for something more server-side so it's usable across multiple platforms and devices.
actually jquery-ajax works like below:-
it takes request and
it gives response.
For Your requirement You also need to follow this steps. so for this , You
send request to PHP page then
send response from php page
so replace Your above jquery-ajax code part with below:-
$('.save').click(function () {
// pulls the value from the textarea
var file = $('#subtext').val();
// send to php to hold text
$.ajax({
url: '/mininote/system/data.php',
type: 'POST',
data: { textbox: file },
success: function(data) {
alert('Saved data to php!');
$('#subtext').val(data);
$(save).text('All changes saved.').show().delay(3000).fadeOut(800);
}
});
});
make sure in Your data.php page textbox value has made echo after inserting data to DB. This process would be something like below:-
data.php
<?php
$textbox = $_POST["textbox"];
/*
perform Your DB inser part here
*/
if(data inserted to db)
{
echo $textbox;
}
?>
Hope this will help You.
You could use the following simple PHP script to accomplish your goal:
<?php
session_start();
if (isset($_POST['textbox'])) {
$_SESSION['textbox'] = $_POST['textbox'];
} else {
echo $_SESSION['textbox'];
}
?>
Another option would be to use HTTP Cookies. Just set the cookie with JavaScript using a plugin or something simple such as, document.cookie = "variable=value"; and access it in PHP with, $_COOKIE["variable"].
Hope this helps.
In the PHP code you could use a PHP session variable like so:
$_SESSION['saveMe'] = $saveMe;
Then get it later, even after a refresh, by using the session variable in php as you would normally use any variable.
For more info see http://www.w3schools.com/php/php_sessions.asp
Use a session, like a temporary cookie, like the following.
session_start();
$_SESSION['sessionName'] = $sessionVar;
Then you can destroy the session with, session_destroy();
See more here.
Why you send it to PHP ?
Just saving in client-side with cookie is better and access in PHP with $_COOKIE
Download jQuery.cookie from :
carhartl/jquery-cookie
and do :
$('.save').click(function () {
// save data from textarea to cookie
var data = $.trim($('#subtext').val());
$.cookie('TEXTAREA_VALUE', data);
});
and go to read by PHP :
<?php
echo $_COOKIE['TEXTAREA_VALUE'];
?>
and to remove :
$.removeCookie('TEXTAREA_VALUE', { path: '/' });
Okay friend !
Ajax is mainly used for sending data without reloading the webpage - from client(js) to serverside(php) or from serverside(php) to client(js). Make sure that name-attribute is given in the textarea and that method is set to post in the form. If I understand your issue correctly you could do something like this:
<?php
session_start();
if (isset($_POST['subtext'])) {
$_SESSION['subtext_value'] = $_POST['subtext'];
}
if (isset($_SESSION['subtext_value'])) {
$subtextValue = $_SESSION['subtext_value'];
}
else {
$subtextValue = '';
}
?>
<html>
<body>
<form action="/mininote/system/data.php" method="post">
<textarea id="subtext" name="subtext"><?php echo $subtextValue;?></textarea>
<input type="submit" value="ok" />
</form>
</body>
</html>
I am trying to post the element information that jQuery pulls, when a user clicks on table cell, to a new page that will use that information (an id in this case) in a sql query. i.e., the user clicks a cell and the job he/she clicks has an id of 25, that is to be passed to my php page that queries the database for the job with that id and then populates the page with said information. The user can then alter the information from the query and submit it to update the database table. I have the id from the click function and a success alert tells me that the info was posted. The problem is that when the page is opened it states that the posted name index is undefined.
Here is my script to get the information:
<script>
$(document).ready(function()
{
$("table.jobs tbody td#job").click(function()
{
var $this = $(this);
var col = $this.text();
var LeftCellText = $this.prev().text();
if (col == '')
alert("Please pick another column");
else
$.ajax(
{
type:"POST",
url:"../php/jobUpdate.php",
data:"name=" + LeftCellText,
success: function()
{
window.location = "../php/jobUpdate.php";
}
});
});
});
</script>
and here is the simple php page it is sending to:
$name = $_POST['name'];
echo $name;
I am new to jQuery, and I cannot figure out why this is not working?
When you use ajax, the second page ../php/jobUpdate.php processes the data sent by the first page, and returns a value (or even a huge string of html, if you want).
The first page receives the new data in the ajax routine's success function and can then update the current page. The updating part happens in the success: function, so you're on the right track.
But in your success function, you are redirecting the user to the 2nd page -- after already being there and processing the data. Redirecting them is probably not what you want to do.
Try replacing this:
success: function()
{
window.location = "../php/jobUpdate.php";
}
with this:
success: function(data)
{
alert(data);
}
If you want to see how to update the first page with the data received via ajax, try adding an empty DIV to your html, like this:
<div id="somestuff"></div>
Then, in the success: function of the ajax routine, do this:
$('#somestuff').html(data);
(Note that the term "data" can be any name at all, it only needs to match the name used in the function param. For example:
success: function(whatzup) {
alert(whatzup);
}
From your comment to my previous post, it seems that you don't need ajax at all. You just need a form in your HTML:
<form id="MyForm" action="../php/jobUpdate.php" method="POST">
<input type="hidden" id="jobID" name="yourJobID">
</form>
Note that forms are invisible until you put something visible inside them.
You can have select controls (dropdowns) in there, or all form elements can be invisible by using hidden input fields (like the HTML just above), which you can populate using jQuery. Code to do that would look something like this:
<script>
$(document).ready(function() {
$("table.jobs tbody td#job").click(function() {
var $this = $(this);
var col = $this.text();
var LeftCellText = $this.prev().text();
//Set value of hidden field in form. This is how
//data will be passed to jobUpdate.php, via its `name` param
$('#jobID').val(LeftCellText);
if (col == '')
alert("Please pick another column");
else
$('#myForm').submit();
});
});
</script>
If you add more values to your form to send over to jobUpdate.php, just ensure that each element has a name, such as <input type="text" name="selectedJobType"> (this element, type="text", would be visible on screen).
In the jobUpdate.php file, you would get these values thus:
$SJT = $_POST['selectedJobType'];
$id = $_POST["yourJobID"];
//Use these vars in MySQL search, then display some HTML based on results
Note that the key referenced in the $_POST[] array (selectedJobType / yourJobID) is always identical to the name specified in the HTML tag. These names are case sensitive (and spelling counts, too).
Hope this isn't TMI, just wish to cover all the bases.
On your success function causing the window to reload will delete any of the variables passed in via .ajax.
What you can try is returning the data and use it in the existing page.
success: function(msg) {
$('#someDiv').append(msg);
}
The reason the index is not defined is because you are using a string in the data-argument, however, that is actually an array-like object. :)
data: { name: col }
that should be the line you need to change. Otherwise I have not seen any problems. Also if I can give you a little idea, I wouldn't use POST actually. In fact, I'd use GET. I can not confirm if that is saver or not, but using $_SERVER["HTTP_REFFERER"] you can check from where that request is coming to determine if you want to let it pass or not.
The way I would suggest is, that you sent the ID in a GET-request and have the PHP code return the data using json_decode(). Now in jQuery, you can use $.getJSON(url, function(data){}) - which is, for one, shorter and a bit faster.
Since you probably will crop the URL yourself here, make sure that you use a function like intVal() in JS to make sure you are sending an intenger instead of a malicious string :)
I've created a php function (called "category_page" in "category-page.php") which reads data from a file into an associative array and then generates some html to display the information on products.php (the page calling the "category_page" function)
My aim is to allow the user to select from a drop down in order to sort the displayed information without refreshing the page.
I have so far managed to achieve this using document.formname.submit on change of the dropdown and then using $_GET to choose which key in the array to sort by, however, this causes the page to reload.
I have a little knowledge of php, javascript/jquery and have done a fair bit of searching/reading on AJAX to enable an update without refresh/reload, but can't seem to put all the pieces together.
So, in products.php, I have the following javascript/jquery:
function sort_products() {
queryString = "?sort_list="+$("#sort_list").val();
$.ajax({
type: 'GET',
url: 'category-page.php',
data: 'sort_list='+queryString
})
}
$("#sort_list").on("change", function() { sort_products() });
and then in category-page.php:
if(isset($_GET['sort_list'])) {
$sort = $_GET['sort_list'];
}
else {
// set default sort order
}
I've verified in Chrome's network panel that a request for category-page.php?sort_list=price is being sent, but the page isn't updating. Any help would be appreciated!
Change this line of code:
$("#sort_list").on("change", function(e) { sort_products(); e.preventDefault(); e.stopPropagation(); });
Once the query is sent, you need to make something with what is returned.
$.ajax({
type: 'GET',
url: 'category-page.php',
data: 'sort_list='+queryString
})
.done(function(data) {
// if your php code returns the html you can make something like this
// the var data will be the html code
$('#your-container').html(data)
})
i am trying to get a button on my page which will eventually be a delete button to work. However because it is a <li> element and not your average submit button with a form etc... i have to use ajax to send all the variables to be processed, at the moment i just want them to be in a state where they can be processed, but at the moment my script doesn't seem to return any value like i want it to and output them.
Hopefully from the code below you will see what i mean, all i need it to do at the moment is just select all the values from the checkboxes which are cehcked and send it to the mail_trash.php, and then just send it back and output the array, just so i can see it is selecting the proper values etc... The actual delete php code is already written and working, this is just to check the Ajax.
Here is the javascript and ajax
<script>
$("document").ready(function (){
$("li.trash").click(function(e){
var db = $(':checkbox:checked').map(function(i,n) {
return $(n).val();
}).get(); //get converts it to an array
if(db.length == 0) {
db = "none";
}
$.ajax({
type: "GET",
url: "mail_trash.php",
data: {'db[]':db },
dataType: "json",
statusCode: {
200: function (response) {
$("#mail_header_name").html(response.mess_id);
}
}
});
});
});
</script>
And here is the script for the mail_trash.php
<?php
include 'connect_to_mysql.php';
$mess_id = $_GET["db"];
echo json_encode($mess_id);
?>
And just to check things the button
<li><a class="trash" href=""> </a></li>
Thank you so much for your help, this has been bugging me for the last couple of hours.
It's not li.trash. It's a.trash because trash is a class of the a element. As such the first three lines of the js should be:
<script>
$("document").ready(function (){
$("a.trash").click(function(e){
and then so on with the rest of you code. I haven't checked the rest of your code necessarily, although I am pretty iffy about $(':checkbox:checked') as I don't think that's correct jquery.... To start off, I'd suggest fixing the first selector I mentioned, checking the second with jquery docs and then jshinting/jslinting your code. (Javascript only)
I don't know if its a typo in the question itself or the issue with your script but name of th e parameter while passing is "db" but on the server side you are expecting "mess_id"
I have a page with multiple forms that do the same thing, acting as a like button for each post in the page, and right next to it the number of likes inside a div named "likes".$id, so I can identify where to write the likes count after the ajax call. I was trying to use jQuery ajax function, but I couldn't set what div to write the results of the function.
$.ajax({
type:'POST',
url: 'likepost.php',
data:$('#like').serialize(),
success: function(response) {
$('#like').find('#likediv').html(response);
}
});
And how would I access the data on likepost.php? I am terrible with javascript, so I hope someone could help me and explain how the jQuery function really works, because I've been copying and pasting it without really knowing what I was doing.
Would this work?
$(function () {
$("#likebutton").click(function () {
var id = $('input[name=id]'); // this is me trying to get a form value
$.ajax({
type: "POST",
url: "likepost.php",
data: $("#like"+id).serialize(), // the form is called like+id e.g. like12
success: function(data){
$("#likes"+id).html(data); // write results to e.g. <div id='likes12'>
}
});
});
});
I put this in the code but when the button is clicked, the usual post refreshing page is done. Why is that?
Making a mini-form, serializing it, and POSTing it seems like a lot of heavy lifting when all you really want to do is send the ID to the likepost.php script.
Why not just retrieve the ID and post it to the script?
First let's break down your function:Type is the type of the request we're making, you specified POST here. This means in your PHP file you'll access the data we're sending using $_POST. Next up is URL which is just the url of where you're sending the data, your php file in this case.
After that is data, that is the data we're sending to the url (likepost.php). You're serializing whatever has a ID of "like" and sending it to the php file. Finally success is a function to run once the request is successful, we get a response back from the PHP and use it in the function to output the response.
As for the multiple forms I'd recommend doing something like:
http://www.kavoir.com/2009/01/php-checkbox-array-in-form-handling-multiple-checkbox-values-in-an-array.html
Here's documentation on the stuff we talked about, if you're every confused about jquery just break it down and search each part.
http://api.jquery.com/serialize/
http://api.jquery.com/jQuery.ajax/
you can try :
function submitform(id) {
var jqxhr = $.post('./likepost.php',$("#"+id).serialize(), function(data) {
$("#"+id).find('#likediv').html(data);
}, "json")
return false;
}
in form:
<form method="post" id="likeForm" onsubmit="return submitform(this.id);">
<input..... />
<input type="submit" value="Submit" />
</form>
in likepost.php add first line:
if ($_SERVER['HTTP_X_REQUESTED_WITH'] != "XMLHttpRequest") {
header("location: " . $_SERVER['HTTP_REFERER']);
exit();
}
you can see more : http://api.jquery.com/serialize/
working for me.