How would I go about permanently add a class to a html element using jQuery.
I am planning on building a image gallery that is sorted into types/categories using the jQuery sorting plugin. I want to add a dropdown box below each image that allows the user to change the type (add/remove class) which permanently changes the HTML for next load. How would I go about this?
EDIT: Ok so from what I can put together I should use this approach:
Jquery add/removes class.
Send full HTML of source via AJAX request.
PHP writes full HTML to file or is there a way to replace only a particular part of a file in PHP?
You could use jQuery's ajax functionality to send back edited HTML to the server to be stored in your database after the user has made their changes.
You can then build up the relevant parts of your page from your database on the next load.
$('#mySelectBox').change(function(){
$.ajax({
url: "updateHtml.php",
data: $('#myEditedHtmlContainer').html(),
success: function(){
// do something on success
}
});
});
You first need to know the distinction between Client side scripting and Server side programming.
The server will return you a set of html on each response which is generated by the server side php in your case.
If you want to modify a class on a certain element, and you want this change to survive the next generated server side php response, you need to somehow inform the server of your change.
There are several options to send data from the client side to the server side.
Store the value in a hiddenfield
Make an ajax request and store the value somewhere on the server so it is aware of this change at the request.
Add it to the querystring of the url being requested.
One solution is to store user decision in cookie. The during very page load, you'll need to check for the appropriate value in the cookie and based on it apply the CSS.
Related
hi I have some problem with my code!
I have a textbox when the user write in this text box I want to retrieve from DB directly without clicking any button.
then some of my form will completed after writing in this textbox.
my JS code :
function centerIDfocus()
{
var id = document.getElementById("centerID").value;
var data = <?php $center_ID = echo mysql_num_rows(mysql_query("SELECT * FROM 'examcenter' WHERE 'id' = '".id."'")); ?> ;
}
window.onload = addEventsToHTML;
in my form:
<input name="centerID" id="centerID" onfocus="centerIDfocus();">
and that’s not working!
any ideas red face
You mixed 2 languages - javascript is run on client side and php on server side.
What You need to do is:
var data = function_to_get_data(); // in javascript
in that function call ajax request to the address of your php script - and only in that php script call your database to return desired data
You're PHP code will only run once, when the pages is loaded, after that it won't run again because there's nothing happening on the server side. If you want to run it each time you get the focus then you should be using AJAX.
Take a look at AJAX gets, I'm pretty sure that's what you want:
http://api.jquery.com/jQuery.get/
It is rather hard to know what you are intending to do, but...
My guess is that you are confused about when things happen and when "onfocus" is fired.
PHP is run on the server when the page is being constructed. In contrast, javascript is run in the browser, either after the constructed page has arrived (onload) or in response to a user click or other event such as onfocus.
Thus there is no way for the javascript (in the browser) to drop into PHP (on the server). For the same reason (and security) it is impossible for javascript to talk directly to the database.
There are two approaches you might take to do what (I think) you are attempting to do.
You could create a javascript array in PHP, indexed by ID, and containing all possible IDs and their data. Use PHP to read the database, and then echo the javascript to define the array. This would become part of the page sent. Then, in response to the event that means you want to fill the field, you extract the data from the array, and put it where you want it. This would be slow for the page to load, but very quick response to the click that triggered the change.
An alternative is to use ajax. The easiest way is to use jquery to send a GET request to the the server requesting the data related to the ID. The server must respond to that URL by extractign the ID, reading the database and generating the reply. I recommend using JSON. Then, when the jquery request returns, the javascript code can move the data from the JSON into your field. This would make the initial page lighter, but would have a fetch delay to the triggering click.
However I think you may also have an issue with the on-focus event. This fires when the user moves the cursor into the field, before they have entered any data. At that point it will contain the data that was set in the HTML. If you can set the ID at that point, you can also set it to the data from the database.
I think you want two fields - one for the ID and another for the looked up data. Then you run the javascript on the onblur event on the ID field.
Hope that helps.
use something like:
$('.centerID').keyup(function(){
var val = this.val();
var url = '/do.php'; // url to a php script
var val = 'action=checkValue&value='+val; // send it the value
$.getJSON(url, val, function(data){
// Something to do when you get the data back
});
});
then just create a php script that checks the database and returns a JSON answer and then do as you please with it.
BTW - I'm assuming you are ok using jQuery. You can apply this to your JavaScript too.
I used keyup() as one example but you can appy this to keydown(), click(), focus(), focusout() etc...
I have a do.php script that contains a switch statement with the possible value of action= and returns JSON. Everything from logging in, registering, activity monitor, to updating a database field without leaving the page.
I have a page which shows a list of items. Page coded with html, css, php and using mysql db.
On that page a user can request to add one of the items to their special list.
I want to do this within the page without having to do a complete page refresh. So user clicks button to add, item is added to their list and button changed so they can't add it again.
Do I use ajax calls to run code behind the page and then refresh the div?
Or is there a better more efficient way to do it.
I'd prefer a php option of possible in case user has js turned off, but don't know if it can be done with using js.
Any help appreciated.
If you want dynamic content (changing the page without refreshing) you are going to have to use Javascript. To do what you are asking, you could call a PHP script via Ajax that outputs the contents of the div with the new item, and then change the div based on that response.
Dagon is exactly right. Create a form which handles the request and set the action of the form to the PHP script you want to handle the request. Note that although this can be the same php script that you use to process your ajax request, it does not necessarily have to be.
Many times when I implement such functionality, I'll set the PHP to send variables as POST (in the event of JS disabled) and have my ajax request as a GET so I can use a single PHP page to handle the 'same' request. When using AJAX, I'll have the script echo a specific code then have the ajax response handle that return.
if(val == 'OK') {
//in event of success, perhaps you want to hide the original form and show a success message
} else {
//do something like unhide a hidden div to display an error
}
If JavaScript is turned off, the page has to be reloaded. In your case jQuery could be very handy and simply rewrite the element you need to rewrite. The server send's a simple json. Using a PHP Framework might also be a good idea, since the way you ask it seems (with respect, and not wanting to offend), that you are not using any framework and might run into falls making your script vulnerable (sql injections for example)
If your visitor doesn't have JavaScript enabled and you want to serve anyways, then you have to do a page reload. First check if that is worth to do, who is your client/visitor, what browser do they use, ... questions like that help you to design your page/app.
Goal: I want to get the text from the selected element and then create a PHP variable from it.
I know how to do this using jQuery but can't wrap my mind around the idea of how to do it in PHP. Basically lets say I have a table with some data. When the user clicks on the data I would like to retrieve that text and then place it in a PHP variable. I could use .text(); from jQuery to create the variable but I could not pass that variable into PHP for further use.
I am very new to PHP (a front-end developer trying to learn back-end). So any explanation would be helpful also.
thanks!
***OK I now understand how to do it. Thanks for the input. I was not thinking. It makes perfect sense to create the variable using a _post and then returning the data via AJAX. Sorry for wasting your time. Thanks for replying.
There is no onclick event in the backend, at least not that works like in javascript
if you want to pass a variable to the server you can use a form and send the data through a GET or POST
Example:
<form action="index.php" method="get">
<input type="button" value="somevalue" name="action" />
</form>
when the user clicks you will see this in the url
www.example.com/index.php?action=somevalue
now you can retrieve this value in php using the $_GET global variable
$variable = $_GET['action'];
The same can be done using POST, this way the variable is not shown in the url
In order to have PHP gather any client side data you would have to pass that data back to the server.
To assign data from client action to a PHP variable, you would first have to capture that data using a front end solution (like your jQuery one above) then pass that information to your server application for processing using AJAX or form submission.
Your PHP data handler could then parse that information out from the data submission and push that info into a variable.
Your front end would look something like
$.ajax({
type: "POST",
url: 'your_file.php',
data: 'selected='+ captured_data,
});
and on your back end...
<?php
...some php code...
$var_to_hold_selected_thing = $_POST["selected"];
...more php code
?>
Specifics of how to do more than that would depend on your application...
You can do it with ajax:
$.ajax({
type: "POST",
url: 'your_file.php',
data: 'text='+ text,
success: function(data) {
alert(data);
}
});
After the .click() event you could have a dialog box appear, with Is this your text?. Then post it.
You could grab that text with jQuery using $(elem).text() as you've described and then pass the captured value to PHP using an AJAX request with jQuery (see $.ajax). The PHP script you pinged with AJAX (either via GET or POST) can then take the value you passed and push it into a $_SESSION variable.
session_start();
$_SESSION["text_clicked"] = $_GET["text_string"];
exit;
After you do this, any subsequent ajax calls made with jQuery (to any PHP script), can recall this variable, provide that you've properly initiated the session.
Stack 101's answer is the correct execution that you're looking for, however it sounds like you could use a little more background on the context first.
Basically, PHP is a server-side scripting language, which means that it gets executed before the page loads into your browser. Here it can look at a database, connect to other sites, or do a whole host of other stuff. Once it's in the browser, your HTML + CSS + jQuery is in charge of displaying + styling + and manipulating that information respectively.
AJAX is usually used to describe the act of posting data to a PHP script, and then re-loading it back into your page without the page refreshing. In other words, jQuery passes data to a PHP script that runs on the server, and then loads in whatever the PHP script outputted. Sometimes PHP can output an entire site (html tags, css, js, whatever). Other times it can simply access a few variables that it got from the POST array, and output a result. This is much more common with AJAX requests.
A quick search turned up this tutorial which might help (I haven't followed it)
http://www.php4every1.com/tutorials/jquery-ajax-tutorial/
Good luck!
I believe it could be done by sending all the required content through GET or POST, and then make PHP stuff it to a variable, however I'm not exactly sure.
PHP runs on the server. Variables come and go each request. Everytime you refresh a page (or send a request otherwise), a PHP script starts running, spits out a response, and stops again. So setting just a loose variable is not really an option.
The options you got are
- Use a cookie. You can set it from Javascript and it will automatically be sent with the next request. Your PHP script can read this cookie.
- Send the variable by doing an AJAX (asynchronous) request. You can send the value in the url or as posted data.
In either case, you can decide to use the variable only once, or store it in a session. I think the cookie will remain unless you explicitly clear it. So you could keep using that.
can any one please help how to get the values from the javascript to php other than while using submit button.
scenario:
i am searching for record, if the record found then, i need confrim alert asking to continue or not, if he click continue how can i say he selected continue
If you want to check without having a page reload, you probably want to execute an AJAX call, then depending on the result returned by the underlying PHP script, take the appropriate action. If you have no knowldege of how to implement this, take a look here
You can never use JavaScript to communicate with the page while it is loading, you can only send a new request to the web server from the JavaScript layer... although you can send that request to the same script that's already running, it will still be a new instance of the PHP script, just like when you open a new browser tab to the same page.
The only way for JavaScript to communicate with PHP at all, is by sending an HTTP request. But you don't have to refresh the page in order to do that if you use AJAX.
AJAX is basically a word to describe JavaScript exchanging information with web pages without refreshing the page. But note that it will still not be able to change variables in the PHP script which is running when the JavaScript code is executed.
In the case of PHP, I've used the open-source library SAJAX which is quite simple. You will find it at http://www.modernmethod.com/sajax/
Hope it helps and good luck!
You can use this as an example using jquery and PHP:
$.post('searchimage.php', { action: 'searchimage', imgreference: $(this).val() },
function(data) {imgsample.html(data);}
);
Basically apply the above function in a document ready function so its run when the page loads.
This can be triggered using $("#prodcode").click() or what ever event handler you want to use.
The php page in my example will get sent the value from imgreference as a post, you can do whatever you want in the php page then return the value which gets added to the imgsample (in this case a td)
hope this helps.
I basically have to do a update of a record. I have a set of controls like textbox, list box, radio button etc. Then i have a button on click of which i need to carry all the updated data into mysql database with a ajax request without page refresh.
I am using the php with codeigniter as my serverside code. On client side i am able to send the ajax request like
$(document).ready(function(){
$('#users_menu').click(
function(){
$('#tempdiv').load('http://localhost//web1/index.php/c1',null);
}
);
});
In the above code the request is placed to a server side php page where i am not able to read the values of the control values (values of textbox, listbox etc). Now this means i should be sending the list with the request. But i am not aware of how to send this request.
Please help me with some details of how to send the list of values or is it possible to read the vaules some how in the serverside php code. For your information i am using codeigniter with my php. Any kind of help is appreciated.
Thanks and Regards
VinodT.
You need to use jQuery .post() function and specify the data to send, see here jQuery.post
You will end up needing to do something similiar to this.
$.post("http://localhost//web1/index.php/c1", $("#testform").serialize());