AJAX - Change content based on reply from PHP Script - php

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;
}

Related

Using JQuery to refresh an HTML form (located on a PHP page)

I'd like to update a form, more exactly I wish to display an extra scroll menu, depending on the user's choice in a first scroll menu.
I have a page, mypage.php page on which there is a form. Here it is :
<form method="post" action="wedontcare.php" enctype="multipart/form-data">
<label for="base">3 - Select a DB </label><br />
<?php
include 'functions.php';
offers_choice_DB();
if (isset($_POST['base_name_choice'])){
offers_choice_table($_POST['base_name_choice']);
}
I have a separated file "functions.php" where are declared all the functions I use here. offers_choice_DB() displays a scroll menu where I can select a database (actually, this function performs a MySQL query and echoes the result in a scroll menu). If the user selects a database, then $_POST['base_name_choice'] exists. And it does, because when i only work with PHP/HTML, all is doing fine.
My purpose is to allow the user to select a database, then for this database I'd like to display a second scroll menu that displays some tables from this DB. This scroll menu will only be displayed if a POST value has been set. The offers_choice_table($_POST['base_name_choice']) function takes this value as an argument, then echoes the HTML for the scroll menu, containing the tables. Here we are !
Oh, and the submit button is not important here, because I want to have my second scroll menu displayed before the user clicks on the submit button, so we just disregard the target page, ok ?
Before, everything was OK : I used tests, conditions (isset...) but it was not dynamic, I had to call other pages, ...etc. And now I want, as you guessed, to use jQuery to refresh mypage.php as soon as the user selects a database so that an extra menu appears.
I started to listen to a change in my scroll menu, but then I don't know what to do to refresh my page with a POST parameter containing the selected database. Anyway, here is my code :
<script type="text/javascript">
$( '#base_name_choice' ).change(function() {
var val = $(this).val(); //here I retrieve the DB name
alert( val ); //I notify myself to check the value : it works
$.ajax({
type: 'POST', //I could have chosen $.post...
data: 'base_name_choice='+val, //I try to set the value properly
datatype: 'html', //we handle HTML, isn't it ?
success: function(){
alert( "call ok" ); //displays if the call is made
//and here...???? I don't know whatto do
}
})
});
</script>
Here it is...any help will be appreciated ! Thanks :)
Regards
The issue here is that your page is rendered first (html + php preprocessing). That means that once your page is rendered, you won't be able to make direct php method calls such as offers_choice_table or change the $_POST parameters.
How you normally do this, is by making an AJAX call from your javascript to a PHP script/method which than generates the second menu based on the parameter that the user chose.
So, you don't need this part:
if (isset($_POST['base_name_choice'])){
offers_choice_table($_POST['base_name_choice']);
}
because you will call "offers_choice_table" method with an ajax call.
You make the ajax call to a url which will return the second menu
$.ajax({
type: "GET",
url: "generate_second_menu.php",
data: { base_name_choice: val},
success: function(data){
alert( "call ok" ); //displays if the call is made
// here you can append the data that is returned from your php script which generates the second menu
$('form').append(data);
}
})
You should use GET instead of POST, in your new PHP file:
if (isset($_GET['base_name_choice'])) {
offers_choice_table($_GET['base_name_choice']);
}
You SHOULD check if the variable has a value set, especially if your function is expecting one. You can use whatever functions you want in this file, it is like any other PHP file you would write. Include any files that you want.
You should make sure to avoid SQL injection when using a GET or POST value in a query: How can I prevent SQL injection in PHP?
In the .ajax() call, there is a callback function success, this runs if the server response is good (i.e. not a 404 or 500). There first parameter in that function is what the server returned. In your case, it would be the HTML you echoed out. You can use jQuery to append the response to an element:
$.ajax({
type: "GET",
url: "generate_second_menu.php",
data: { base_name_choice: val},
success: function(data) {
// it looks like you're only returning the options of the select, so we'll build out the select and add them
var $newSelect = $('<select></select>');
$newSelect.append(data);
// and then add the select to the form (you may want to make this selector for specific)
$('form').append($newSelect);
}
});

Count click on iframe PHP

I have a file with title ad.php and contains
<img src="bannerimg.png">
and in another file i have:
<iframe src="ad.php"></iframe>
Question is how to count click on iframe!
Just do this if using javascript....
var clik = 0;
$('#myframe').click(function(){
clik++
alert(clik);
});
UPDATE WITH AJAX
$(document).ready(function(){
$('#myframe').click(function(e){
e.preventDefault();
$.ajax({
url : "countclick.php",
success: function(){
alert('done');
}
});
});
});
Then in your php file countclick.php you just retrieve the current value from database, and increment it and update.
Or just execute an increment query directly, without retrieving current value
Im assuming you know how to do that in php/mysql , so Im not gonna post that part
You would have to catch the click event somewhere on the client side (in JavaScript most likely) and then send a request back to the server notifying it of the banner click.

callback race: button click to trigger ajax, whose callback won't execute on time

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.

Repopulate a div after an ajax form is submitted using ajax (I think!)

I have a table with a bunch of products from my database table. Each product has an update button which will produce a populated form via ajax for the user to ammend any details they wish.
On submit, I want to update the database and then return back to the page I was just on showing real-time updating data. With anything else I do, I send back a view to the ajax success function and it gets displayed. Only I can't seem to do it with this. I take the action and method out of my form tag and let an ajax function handle it, but it doesn't return a view, it just displays the view only, whereas I want my div to go into a specific div on the existing page
/***** submit update form *****/
$(document).on('click', '#updateSubmit', function() {
$.ajax({
type: "POST",
url: 'products/updateProduct',
success: function(data) {
$('#viewProducts').fadeIn(1000, function(){
$(this).html(data);
// THIS IS WHERE I WANT MY VIEW TO BE RETURNED TO(the #viewProducts). CAN THAT BE DONE?
})
} // end success
}); // end ajax
}); // end submit event
Try to use
url: '/products/updateProduct' in place of url: 'products/updateProduct'
if still not works try to use full path in place of relative path............

Run a function after a page refresh

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 }
});

Categories