Using jQuery to store basic text string in mySQL base? - php

Could someone point me in the right direction here?
Basically, I've got this jQuery code snippet:
$('.bggallery_images').click(function () {
var newBG = "url('" + $(this).attr('src');
var fullpath = $(this).attr('src');
var filename = fullpath.replace('img/Bakgrunner/', '');
$('#wrapper').css('background-image', newBG);
// Lagre til SQL
$.ajax({
url: "save_to_db.php",
// The url to your function to handle saving to the db
data: filename,
dataType: 'Text',
type: 'POST',
// Could also use GET if you prefer
success: function (data) {
// Just for testing purposes.
alert('Background changed to: ' + data);
}
});
});
This is being run when I click a certain button. So it's actually within a click handler.
If I understand this correctly, this snippet takes the source if the image I just clicked and strips it so I end up with only the filename. If I do an alert(filename), I get the filename only. So this is working ok.
But then, it does an ajax call to a php file called "save_to_db.php" and sends data: filename. This is correct right? Then, it does a callback which does an alert + data.
Does this seem correct so far?
Cause my php file looks like this:
<?php
require("dbconnect2.php");
$uploadstring = $_POST['filename'];
$sessionid = $_SESSION['id'];
echo ($sessionid);
mysql_query("UPDATE brukere SET brukerBakgrunn = '$uploadstring' WHERE brukerID=" .$_SESSION['id']);
mysql_close();
?>
When I click the image, the jQuery snippet fires and I get the results of this php file as output for the alert box. I think that the variables somehow are empty.
Because notice the echo($sessionid); which is a variable I've created just to test what the session ID is. And it returns nothing. What could be the issue here?
Edit: I just tried to echo out the $uploadstring variable as well and it also returns nothing. It's like the jQuery snippet doesn't even pass the variable on to the php file?

You're trying to send just the filename, but you're retrieving a named form field in your PHP code. So you need to send a named form field:
Change your ajax call like this:
$.ajax({
url: "save_to_db.php",
// The url to your function to handle saving to the db
data: {filename: filename}, // <= Change #1 (give jQuery a simple object)
dataType: 'text', // <= Change #2 ('text', not 'Text')
type: 'POST',
// Could also use GET if you prefer
success: function (data) {
// Just for testing purposes.
alert('Background changed to: ' + data);
}
});
Your PHP script will now receive a POST varible called filename whose value comes from your filename Javascript variable. (You can also use $.post to do this, but it's just a wrapper for ajax anyway...)
Passing a simple object into the ajax call is the easiest way to send fields to the server. jQuery will take the object and create the URL-encoded form data (doing all of the escaping for you) by using the object's keys and field names. So for instance, if you give it this object:
data: {a: 1, b: "testing one two three", c: 3}
...it sends this URL-encoded data:
a=1&b=testing+one+two+three&c=3
(Note how it encodes it for us.) More in the ajax docs (but beware, at present what the docs say about array handling is wrong; see this bug report for details).

Related

Update Hidden Field Value Inside PHP Function

I am new to php and am trying to update a hidden field value inside a php function and can't see to find a solution that works.
In template.php I have:
<input type="hidden" id="variable_ID" name="variable_name" value="variable_value">
This works fine.
However I need to update the value of the variable to the record ID of inserted record in a function in functions.php eg
function myFunction() {
$insert_record = $mydb->query("INSERT INTO `Table`(`Name`) VALUES ('John')");
$get_record_id = $mydb->insert_id;
// *** Set Hidden field value to $get_record_id here ***
}
I have tried a myriad of things but can't seem to find a solution.
Any pointers on how to solve this problem?
Here is the solution I used - thanks to #Steven and #El_Vanja for direction.
(I may need to change the question title now though because what I actually needed to do was return a variable to javascript from PHP using Ajax. I didn't need to use hidden fields).
PHP
function myFunction() {
$insert_record = $mydb->query("INSERT INTO `Table`(`Name`) VALUES ('John')");
$get_record_id = $mydb->insert_id;
echo json_encode($get_record_id);
exit;
}
JS
jQuery.ajax({
url: ajax_url,
type:'POST',
data: {
action: "myFunction",
anydata:"to be posted"},
success: process_record_ID
});
function process_record_ID(data_returned_from_myFunction){
recordID = data_returned_from_myFunction;
}
Hope this helps others!
Notes
I believe that we have to declare 'process_record_ID' as a separate function outside of AJAX because AJAX is asynchronous. If we define the function in the success handler, the function runs in AJAX before the value is actually returned from PHP.
In the AJAX success handler, we don't need to explicitly list the 'data_returned_from_myFunction' variable in the call to process_record_ID function. When the data is returned to the AJAX success handler from PHP, it still gets sent to the function.
Additional answer
You're correct AJAX is an asynchronous construct which means that certain tasks can be carried out before you might expect them to (from a synchronous perspective).
For example we can (as per the code in the original answer) use jQuery to update the value of a field directly in the success handler.
We can't update a JS variable directly, i.e:
some_variable = response.value;
If you attempt it the variable some_variable will likely be undefined.
The difference comes down to callbacks:
Callbacks allow the asynchronous function to call a function after it completes. Where as setting a variable happens on the spot.
There are two easy ways to solve this issue then:
Create a function outside of the AJAX request and allow it to callback that function once the AJAX request has completed -- as you've already discovered.
Use the complete option inside of your AJAX request.
Using a call back
Firstly we need to define out variable to be updated and the function which we will use to update it:
var inserted_id = "";
function update_id(data){
inserted_id = data.record_id;
}
Then we can make out AJAX call:
$.ajax({
type : "POST",
url : "/url/to/functions.php",
data : {data:"to be posted"},
dataType: 'json',
success : update_id
});
N.B.
Calling update_id in this fashion means we pass the entirety of the returned JSON object; not just the returned number.
Alternatively...
var inserted_id = "";
function update_id(data){
inserted_id = data;
}
$.ajax({
type : "POST",
url : "/url/to/functions.php",
data : {data:"to be posted"},
dataType: 'json',
success : function(response){
update_id(response.record_id);
}
});
This method is effectively the same but we only pass the returned number to the update_id function.
Using complete
complete works the same way as success however activates once the AJAX request is... complete...
var inserted_id = "";
$.ajax({
type : "POST",
url : "/url/to/functions.php",
data : {data:"to be posted"},
dataType: 'json',
complete: function(data) {
inserted_id = data.responseJSON.record_id;
}
});
Original answer
Having not seen the rest of your code giving a complete answer is tricky. However, this should set you on the right track:
PHP
Firstly, in your PHP you need to make sure and output the data that you want returned to the webpage. In this case we want to return the insert id of the newly created record; to do this we're going to output a JSON object so that the AJAX call can interpret the value and update the page:
function myFunction() {
$mydb->query("INSERT INTO `Table`(`Name`) VALUES ('John')");
echo json_encode(["record_id" => $mydb->insert_id]);
exit;
}
N.B.
We don't want any output other than the JSON string. Hence exit has been used after the echo. You may want/need to adjust the echo and exit to fit with the rest of your code etc.
JS
Now that we have our PHP returning usable data to our ajax call (which should look something like the below) we can take the returned data aka response and update the value of the hidden field accordingly.
$.ajax({
type : "POST",
url : "/url/to/functions.php",
data : {data:"to be posted"},
dataType: 'json',
success : function(response) {
$("#id_of_hidden_field").val(response.record_id);
}
});

Sending data ajax

I have a page called post-blog.php, in here I've set-up a blog entry. I have all this data being saved into one variable. Its displaying this data in an array.
var data = title + content + image + datetime + categories;
How can I send this data to another page called publish.php and redirect the user to that page ?
I've tried to set up a ajax to do this but its not working. Any suggestions ?
$.ajax({
type: 'POST',
cache: false,
url: 'publish.php',
data: data,
success: function( data ) {
alert ( data );
}
});
return false;
});
As per my understanding of the problem, you need to pass the data to a new page and open that page.
If this is your question then this can be done without AJAX, basically AJAX does not even provide solution here. Instead you can just pass all the data to your new page in query format as below -
var page = 'publish.php?title='+title+ '&content='+content+'&image='+image+ '&datetime='+datetime+'&categories='+categories;
Then just change the window location as below
window.location.href = page;
And to get all those variables in your PHP file, do the following in publish.php on top -
if($_GET['title'])
{
$title = $_GET['title'];
}
// similarly get all the data in publish.php file and continue with your page
I am assuming all your variables are strings. If they are not, for example the datetime may be an object, change them into a string first.
Docs say Object must be Key/Value pairs or a string.
Objects work well for this, try something like:
var data = {title: title, content: content, image: image, datetime: datetime, categories: categories};
If your data is coming from a form check out jQuery's serialize.
I've never tried to pass as a string in a POST, but my gut feeling is it would need to be in a format similar to passing the data through the url.
var data = 'title=' + title + '&content=' + content;
Also keep in mind the data in the success function is not the same as what is being passed to the php page. This is what the php page will return. If you're php page returns nothing your alert will be empty. When I'm testing I like to throw something like echo $_POST['title']; in the php file to see something come back.
Here is a similar question that might help too.

jquery ajax variable to php

I'm stuck since 2 weeks, since i decided to use a nice threeview based on the jquery library.
My problem is what i'm trying to get the value of an selected folder as an variable to php.
I'm able to get the value and show it via an Alertbox in Jquery but the value is not posted to the PHP variable. echo shows nothing.
Text under is just to clarify why i need to use this solution with php and so on.
Then this is solved i will keep on struggling to get the whole path that i later will send to a bash script what is already finished. It creates a text file with metatags from an flac or mp3 album for my SQL db already done and working. This app is local for maintainance of the database.
To my problem and code (bear in min what jquery and ajax is totally new for my)
filename: file_browser.php
Jquery part
<script>
$(document).ready(function()
{
$("button").click(function()
{
var dir = ($(".active").text())
$.ajax({
type: "POST",
url:"file_browser.php",
data: dir,
success: function(data){
alert(dir); dir }
});
});
});
</script>
PHP code
<?php
echo "<form>
<button>Append</button>
<div id'japp'>";
if (isset($_POST['dir'])) {
$dir = $_POST['dir']; }
echo $dir;
echo "</div>
</form>";
?>
I will keep on trying, now i at leasthave an chance to get some help to avoid taking one more week on this :).
From the jquery website on $.ajax.
By default, Ajax requests are sent using the GET HTTP method. If the
POST method is required, the method can be specified by setting a
value for the type option. This option affects how the contents of the
data option are sent to the server. POST data will always be
transmitted to the server using UTF-8 charset, per the W3C
XMLHTTPRequest standard.
The data option can contain either a query string of the form
key1=value1&key2=value2, or an object of the form {key1: 'value1',
key2: 'value2'}. If the latter form is used, the data is converted
into a query string using jQuery.param() before it is sent. This
processing can be circumvented by setting processData to false. The
processing might be undesirable if you wish to send an XML object to
the server; in this case, change the contentType option from
application/x-www-form-urlencoded to a more appropriate MIME type.
I'm assuming the value of $(".active").text() is just the value you want to pass without any key paired to it. Format your string in a key/value pairs as shown above and you should be great.
If you need your $_POST array to contain a dir element, you need to send a key - value pair to your script:
var dir = { "dir": $(".active").text() };
You should try this:
<script>
$(document).ready(function()
{
$("button").click(function()
{
// setting a key-value
var dir = { dir: $(".active").text() };
$.ajax({
type: "POST",
url:"file_browser.php",
data: dir,
success: function(data){
alert(dir);} //removed the second 'dir'
});
});
});
</script>
The solution is
{
$("button").click(function()
{
var dir = ($(".active").text()); // from my question (gives name of selected dir)
$.ajax({
type: "POST",
url: "file_browser.php",
data: { dir: "dir" },
success: function(response){ // function(response) was (data)
$('#japp').html(dir); // points to the forms id="japp"
alert(dir); }
});
});
});
Question above solved.
My other mentioned problem
Getting full path instead of just dir. Partly solved.
Gives the hole path as string with dir (wanted) + the dir one more time (not wanted).
It also gives website url i think instead of root (/) (not wanted) + visible path on webpage from filesystem (wanted).
This can be solved with an regex in php but i will first try to make it cleaner by getting only the wanted stuff with this jQuery function.
Left my almost done solution here just to give a hint there to begin if needed.
var dir = ($(".active").parent('li').text());
Thanks for all help and for leading me on the right way #Frank B, #jeroen & #Zim84

Getting a value from a variable , send to php to process and add that value to mysql database?

i am new to php and mysql.
How can i extract a VALUE from a JAVASCRIPT VARIABLE(i set) then send it to a PHP page that can read it and process it , the PHP will then insert the value into a table in MySQL database.
var A = "somevalue"
I have been researching but none of it give me a simple and direct answer . I saw some people uses JSON(which i am unfamiliar with) to do this.
Hopes someone can give me an example of the javascript/jquery , php code to this. Thanks!
You've asked for... a lot. But, this tutorial looks like it could help you.
(FYI -- I swapped out the original tutorial for one on ibm.com. It's better but far more wordy. The original tutorial can be found here)
I'm not pretty sure if it works but just try this. Your jQuery script shoul be like this:
$(function(){
var hello = "HELLO";
$.post(
"posthere.php",
{varhello: hello},
function(response){ alert(response); }
)
});
and "posthere.php" is like this:
$varhello = $_POST['varhello'];
echo $varhello . ' is posted!';
you should then get an alert box saying "HELLO is posted!"
What you need is Ajax. This is an example jQuery to use:
function sendData(data) {
$.ajax({
type: 'POST',
data: data,
url: "/some/url/which/gets/posts",
success: function(data) {
}
});
}
This will send post data to that url, in which you can use PHP to handle post data. Just like in forms.
If you have a form:
<form id="theformid">
<input type="text">
</form>
Then you can use jQuery to send the form submit data to that sendData function which then forwards it to the other page to handle. The return false stops the real form from submitting:
$("#theformid").submit(function(){
sendData($(this).serializeArray());
return false;
});
If you though want to send just a variable, you need to do it like this:
function sendData(data) {
$.ajax({
type: 'POST',
data: {somekey: data},
url: "/some/url/which/gets/posts",
success: function(data) {
}
});
}
Then when you are reading $_POST variable in PHP, you can read that data from $_POST['somekey'].
Inside the success callback function you can do something with the data that the page returns. The whole data that the page returns is in the data variable for you to use. You can use this for example to check whether the ajax call was valid or not or if you need to something specific with that return data then you can do that aswell.

What is correct way to pass data through .ajax() to a PHP script?

I'm attempting to send a piece of data through jQuery .ajax() to a PHP script which will then be loaded into a div container. The PHP script will then run with this piece of data and its contents will be returned into the aforementioned div container.
Initially, I wrote this piece of code (shown below) which successfully added the correct elements upon a click but wasn't able to name them correctly because it didn't doesn't pass the count_bucket variable to the PHP.
var count_bucket = 4;
var loadPHP = "create_new_bucket.php";
$(".add_bucket").click(function(){
count_bucket++;
$("#tree_container2").append( $('<div id="bunch' + count_bucket + '">').load(loadPHP));
return false;
});
I then altered the code to this (shown below) in attempt to pass the count_bucket variable to the PHP script.
var count_bucket = 4;
$(".add_bucket").click(function () {
count_bucket++;
var bucket_add = $.ajax ({
type: "GET",
url: "create_new_bucket.php",
data: var count_bucket,
dataType: "json",
async: false,
}).responseText;
$('#tree_container2').append( $('<div id="bunch' + count_bucket + '">').load(bucket_add));
});
The PHP file create_new_bucket.php looks like this:
<?php
include_once "test_functions.php"; // include functions page
$i = $_GET["count_bucket"];
drawBunchNew($i);
?>
I'm unclear which aspect of the .ajax() is incorrect. I suspect I'm not collecting the variable correctly in the PHP or I'm using the incorrect syntax to pass it to the PHP file. If anyone could help me identify the error, I would greatly appreciate it.
*UPDATE******
Thanks Tejs & Tandu. I'm clear on how to structure the data now but I still am having trouble getting the whole bit of jQuery to work. I took Tandu's suggestion to use .load() instead and have changed my PHP to use POST to pull the data but it's still not working correctly.
var count_bucket = 4;
$(".add_bucket").click(function () {
count_bucket++;
var bucket_add = $.load ("create_new_bucket.php", {count_bucket: count_bucket}, }).responseText;
$('#tree_container2').append( $('<div id="bunch' + count_bucket + '">').load(bucket_add));
});
And the PHP is:
<?php
include_once "test_functions.php"; // include functions page
$i = $_POST["count_bucket"];
drawBunchNew($i);
?>
Final working jquery I used (final PHP is same as above):
var count_bucket = 4;
var loadPHP = "create_new_bucket.php";
$(".add_bucket").click(function(){
count_bucket++;
$("#tree_container2").append( $('<div id="bunch' + count_bucket + '">').load(loadPHP, {count_bucket: count_bucket}));
return false;
});
The data property of the ajax request is going to be an object; think of it like JSON:
{ data: var response }
Is not valid JSON. However, you can do something like this:
data: { myKey: 'myValue', myKey2: 'myValue2' }
Or in your situation:
data: { count_bucket: 4 }
And it will send the data contained in the data property to your server as part of that name value set.
Data for ajax in jQuery needs to be passed as a query-string formatted string ('key[]=value&key[]=value&key[]=value') or as a json object ({key: [value, value, value]}). I believe that the var you have there will be a syntax error. You also need to specify the key, so either data: {count_bucket: count_bucket} or data: 'count_bucket=' + count_bucket should do.
Note that it is not necessary to use .ajax(). It's usually a bit nicer to use .load(), .post(), and .get(). In your case, .load() should work fine. Pass the data as the second argument.
Why do you not want the request to be asynchronous? Note that dataType is the data type of the return value, not of what you are sending. Are you receiving json? jQuery can also usually guess this correctly, and if you set the header on the php side, it helps a lot. The GET type is also the default.
Final note: when using .load(), if you pass the data as a string it will use GET, but if you pass it as an object it uses POST.

Categories