Alright guys, so I have a page that uses php functions with jquery functions.
The jQuery functions or simple confirmation boxes and dialog boxes. So what I need now is when an user clicks a button, I need to show a confirmation box.
Then when the user accepts, I run a php function that ends with a page refresh then I want to show a dialog box to show it has been done.
But now what happens is that, the confirmation boxes appears. When users accepts, the dialog box starts to show but right then, the page refreshes...
Here is the php function thats gets called when users clicks ok from the confirmation box:
function resetText()
{
$url = curPageURL();
?>
location.href='<?php echo"$url"; ?>'
message();
<?php
}
Thanks for your help.
I think you might be trying to use web technologies in a way they weren't built to be used. The web is built on a client-server model; in your case, php only runs on the server, and javascript (and jQuery) only runs on the user's web browser. In order to call php from javascript, you'll have to do so in the form of a new web request.
You'll want to move whatever it is you wanted to do in php to a different url endpoint that you can call, say, /callback.php, which after some thought returns something like:
{ 'myUrl': 'http://stackoverflow.com' }
Then, your jQuery will look something like:
$('#myButton').click(function()
{
if (confirm('My confirmation message'))
{
$.ajax({
type: 'get',
dataType: 'json',
url: '/callback.php',
success: function(result)
{
alert('You\'re about to go to ' + result.myUrl);
window.location.href = result.myUrl;
},
error: function(request)
{
// handle somehow
}
});
}
});
Clint is right - PHP is server-side, so you'd have to run the function via an ajax call.
Still though, if that can work for you and if you want to see the popup box on a refresh, you could set a session variable before the refresh is performed then do something like:
$(document).onReady(function(){
if (isset(that session var)){ show that popup, remove session var }
});
Related
Scenario
I have a page where users can activate or deactivate the service. I have got a button where it says the current state of the service. I achieve this by getting service state via php and echoing active or inactive at the place of the button text.
Problem I want a AJAX to listen for click on the button. When a user clicks on the active button the AJAX should call a url which triggers change of the users' service state change and returns the current state of the user. I want to change the text in the button to active if the reply was 200 and inactive if the reply from the php was 101.
I want to compare the result in a if-elseif-else style statement like
if(reply=='200')
code-to-change-the-text-to-active;
elseif(reply=='101')
code-to-change-the-text-to-in;
else
alert(some-error);
I made several searches and only found how to change the text with the text from the reply. But, I want a way to fetch the reply as variable and use it to switch my text.
You need to send your reply from PHP to JavaScript as JSON (using json_encode($reply)), then, your AJAX success callback function will receive the state value in a format it can use.
Use the following code format with your actual data:
HTML
<input type="button" value="active" id="active">
JS
$('#active').click(function () {
var status = $(this).attr('value'); // get the value of your button state
var r = confirm("Are You Sure Change Status?");
if (r==true){
$.ajax({
type: "POST",
url: "YOUR URL",
data:"{userstatus:status}",
beforeSend : function () {
},
success:function(result){
//Do whatever you want with result//
}
});
}else{
return false;
}
});
Note: when you click on the active button its call ajax function and put your actual url file name in url param. then run the sql query there and you will get response in success as result.
shortcut/ fast.
JS
function updateStatus(){
$.get('yourPHPCode/getStatus', function(data) ){
$('#status').val(data);
}
}
PHP
function getStatus(){
...
echo $status;
}
I have what I think is a fairly classical problem involving what looks to me like a callback race, but in spite of all my reading, I'm still stuck. You'll find the code pasted below.
It's a simple log in form and you can see that when a certain button is clicked, I'll send the form data "ajaxically" to an external php file. Once the php has run, I'm to receive the results back, and as a test here, to simply alert out the email address from the php file.
When I run this, the ajax callback doesn't execute. If I click the button fast and repeatedly, I get the right alert. I also get the right response if I put in an extra alert.
How do I get it to run without doing these other silly things?
Thanks in advance
RR
$('#'+this.loginForm[0].parentId+"logIn")
.on('click', function() {
var jax = $.ajax(
{
type: "POST",
url: "../sharedfunctions3/act-membership.php",
data: {email: document.getElementById(that.parentId+'email').value,
password: document.getElementById(that.parentId+'password').value,
path: that.path,
action: "logIn"
}
});
jax.done(function()
{
obj = JSON.parse($.trim(jax.responseText));
alert(obj.email);
});
jax.fail(function() { alert("error"); });
alert(1);
});
I had a hunch that when you clicked the button the browser was submitting synchronously and asynchronously.
The return false; tells the browser to not submit the form and to prevent default actions from there on.
When a button inside of a form tag is clicked, most browsers will submit the form even though it is not a submit input.
I have 3 tasks :
1) Submit the message in a textarea when the user press enter button on keyboard or click "submit" button.
2) Use php/mysql to save the message onto database.
3) After save it onto database, need to show the updated message onto the website back.
The problem is... There is no php script that can change "Enter" button event, so I need to use javascript, if I use javascript, I need to create a new page sendMsgToDB.php to submit the data to database by the following javascript/ajax :
<script type="text/javascript">
function gg(e) { //sumbit the form when user press Enter button
key = e ? e.which : window.event.keyCode;
if(key==13) {
$.ajax({
type: "POST",
url: "sendMsgToDB.php?msgid=" + msgid,
data: dataString2,
success: function() {
$('textarea.resposting').val('');
}
});
}
}
$(function() {
document.getElementById("resposting").onkeypress = gg;
});
</script>
I use mysql to retrieve 10 latest messages from database and use pure php to display the messages onto the website. If I want to show updated messages onto website after the user submit the data through the textarea by pressing "Enter" button on keyboard, sure I need to call the function Display_New_Msg() after the data is complete send to database. If I use Javascript/ajax to sumbit data, how to use javascript/ajax/jquery determine whether or not the data is complete send to database?
Seriously I don't like to use javascript/ajax/jquery, but I force to use them because I need to change the "enter" button event, is there a way to change "enter" button event by using php? How to make the press "enter" button act like click "submit" button to submit the form <form name="frmMsg" action="currentPage.php">, the action will go to the currentPage.php, so the page is refresh, so it will re-execute the function Display_New_Msg() automatically to show the new message, so don't need to dertermine whether or not the data is complete send to database anymore.
If I use Javascript/ajax to sumbit data, how to determine whether or not the data is complete send to database?
It all comes down to the response from the resource that's handling the AJAX request. In this case, sendMsgToDB.php. That script needs to make sure it's doing what it needs to do and that everything's getting into the database (usually a lack of error is sufficient), then sending a response accordingly. If there is an error on the server, return an HTTP error code (such as a 500 server error) to indicate this.
The jQuery .ajax() call then determines the call-back function to use based on the response from the server. Your code currently handles a successful response:
success: function() {
$('textarea.resposting').val('');
}
In order to handle an error response, you'd want a second callback for error:
error: function() {
alert('There was an error!');
}
The HTTP response codes exist for exactly this purpose, so that clients consuming those responses can easily determine the status of the request.
Edit: Conversely (and perhaps more to the spirit of your question, if I'm now re-interpreting you correctly), you can use the jQuery submit() function to submit the form in your key press logic. That way you don't have to use AJAX and can just use a regular form submission and response, which you indicate to be your preference. Something like this:
if(key==13) {
$('#myForm').submit();
}
I am working on a project for reserving classrooms. One way of reserving a room is to select a room, see if the things it has (# of seats, # of computers, etc.) is ample for whatever the person needs it for, and then make a reservation.
I have a page that displays all of the available rooms as links in an HTML table, created dynamically in PHP/MySQL. My goal is when a user clicks on a room name, the AJAX request executes a query and returns the necessary data, and then displays it in a DIV on that same page.
Right now, I'm calling an external PHP file that gets the ID of the room that's clicked and executes the query. I'm still very much a novice at jQuery, and I'm pretty sure the problem is in my jQuery script:
<script type="text/javascript">
$(document).ready(function()
{
$('table.roomNums td a.rm-details').click(function()
{
var id = $(this).attr('id');
$.ajax(
{
type: 'POST',
url: 'roomInfo.php',
data: {
roomID: id
},
dataType: 'json',
cache: false,
success: function(result)
{
$('#room-details').empty();
$('#room-details').append("<ul>\n\t<li>Seats: " + result.numOfSeats + "</li>\n</ul>");
}
});
});
});
</script>
As of now, when I click on one of the room number links, nothing happens. I'm assuming that my problem resides in this script, but I'm not sure where or what. I've been reading into the ajax function in jQuery and I'm pretty sure I understand what's going on, but I'm having no luck at the moment.
You want to troubleshoot the following four things:
The HTTP Request Does the browser even issue an ajax request? If so, does it contain the form parameter you are trying to make it contain?
The HTTP Response Does your php script return the data you are expecting in JSON format so JQuery can automatically parse it for you? Copy and paste the response from the server into a test javascript file and see if it compiles as a valid JSON object in a javascript debugger.
AJAX success function Does your javascript error out? Can you step through each line of execution in a javascript debugger like firebug?
Click Event Handler Does your click handler properly return false so the page does not reload? Does your click event handler function fire at all upon click?
Somewhere in the above four things lies your issue. It looks to me like you just need to return false in your click handler so the page does not reload.
Is there a way to send data to database when click on a link without page refresh?
I use php/mysql...
I will give you an example using jQuery.
Let's say that we have a link with an attribute id="button_id" (you have to learn the jQuery selectors ).
$("#button_id").click(function(){
var var_data = 5;
$.ajax({
url: "my_script.php",
data: { var_PHP_data: var_data };
success: function(data) {
// do something;
alert(data);
},
});
});
Explanation: you will send the variable var_data with the name var_PHP_data to a my_script.php without page refresh using an ajax call (using GET method).
This is very simple example of what you have to write on your PHP script.
<?php
$var_name = $_GET['var_PHP_data'];
echo 'This is what you have send'.$var_name;
?>
Because the default method to send variables in the ajax function in jQuery is GET.
We have to use the $_GET function in PHP.
This php script will print a message and this message will be handled in the success: function in the Ajax call and just for example we will alert this message returned from PHP.
You'd have to use JavaScript. When a user clicks a link, if you don't use JavaScript, then you need to go user -> server -> user and they get a whole new page.
HTTP is stateless.
It's not possible without a page refresh but this is the classic use-case for AJAX requests. If you're not familiar with AJAX then there are various methods of doing this using all the popular JavaScript frameworks such as Prototype and jQuery
You can't send data directly to a database, but you can use AJAX to send data to a php page that will save them to the database, without reloading the page or following the link in the browser..
Have a look at http://api.jquery.com/jQuery.post/
Not using PHP because it is server side - you need JavaScript / AJAX for this.
Check out frameworks like dojo (http://www.dojotoolkit.org/) , mootools (http://mootools.net/) or jQuery ( http://jquery.com/ ).
Yes, you can use AJAX.
This is a very big topic, but I'd recommend you do some research on AJAX and jquery (javascript).
Here are some tutorials:
http://www.ajaxf1.com/tutorial/ajax-php.html
http://www.talkphp.com/vbarticles.php?do=article&articleid=58&title=simple-ajax-with-jquery
Do a search in google for more info.