How to check data server side before opening a javascript window - php

I have an issue going on here. I am using PHP to get values from a database in a php script. What I would ideally like to do is test to see if there is any data to display server side and if there is, pop up a javascript window with the values.
I have this working right now with javascript. Currently, the user can look up data and presses a submit button with an onclick event attached to it that opens the javascript window. I'm also using getemementbyID to grab the value posted in the parent window that gets passed to the child window. Basically, the php script is getting bypassed so I can't really do any checks of the data. Bottom line... I want to check to see if data is present BEFORE the window opens, if possible.
Any ideas?

your best option is to either make a request via ajax to check for data or make the request on the initial page load so you know already and can pass this to your click handler.
edit - This is an example using prototype (untested):
$('button').observe("click",clickCheck);
function clickCheck(){
new Ajax.Request("/remote/url", {
method: 'get',
onSuccess: function(transport) {
if (transport.responseText == 'results returned'){
// launch popup
}else{
// dont launch popup
}
}
});
}

I suggest using jQuery for making an ajax request. Something like:
$("#my-button").click(function(){
$.get('page_with_the_data.php', function(data, textStatus){
if (data) {
// Open the pop-up
// ..or just: alert(data)
} else {
// empty page
alert("No data returned");
}
})
})

Related

Why my AJAX function blocks the header of PHP that I have on my page?

I am doing a program in PHP (MVC) in which I need to delete a row from the database when I click on a link on the View side. So, when I click on the link, the following ajax function it is called.
var deleteCar = function(id)
{
$.ajax({
type: "POST",
url: "http://localhost/project/car/deleteCar/" + id,
success: function(response){
}
});
}
but I do not want to send any data so it is the reason why I put it as above.
Then, in the Controller side I have the following method:
public function deleteCar($id)
{
//Here I call the function to delete the Car that I send by id. It works fine.
header('Location: http://localhost/project/car');
}
If I call directly the method deleteCar on the link without Ajax the header works properly but in the same moment I use Ajax to call it, I have to refresh the page to see the content that I have modified, I mean, that the Car have been deleted.
The code works fine, just I do not want to refresh the page after AJAX function had finished.
Thanks in advance!
I am guessing the use case is to allow the app to work when the user does not have JS enabled - so they just click the links and get a non-AJAX experience. In this case you probably want to redirect ONLY if the page was requested via GET, not POST. something like
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
header('Location: http://localhost/project/car');
}
is likely what you are looking for.
You will then have to actually remove the element representing the car from the DOM in your success handler, with something like:
var deleteCar = function(id)
{
$.ajax({
type: "POST",
url: "http://localhost/project/car/deleteCar/" + id,
success: function(response){
$('#car-row-' + id).remove();
}
});
}
(that won't be it exactly, it depends how the HTML of your page is setup how exactly you will do this).
I believe the key thing to understand here is - when your PHP function has completed it has removed the car from the database, but the browser still has the same HTML it got from the page originally. Just sending an AJAX request won't change that. If you want the HTML in the browser to change to reflect the new state of the database, you will NEED to do one of two things:
Refresh the page, so the entire thing is rebuilt by PHP based on the current database state
Use javascript to change the HTML in the browser, to reflect the changes you have made to the database state.
It is wrong on so many levels but it's difficult to put in words. It's subtle.
Long story short - think about jquery.ajax as of another virtual tab of you browser.
When you make ajax-request to the server - you create new virtual tab.
You php header could affect this virtual tab and redirect it where that header defined.
But it will redirect that virtual tab, not your current tab - if that makes sense.
What are your options? On success - make redirect with pure javascript.
success: function(response){
location.href = "http://localhost/project/car";
}
This would be the basic way to solve your problem.

Image wont change

I am trying to get the image links from 9gag (what also works) and when I click on a button the image changes to the next one. The basic problem is that it works only once. I can then switch between the 1st and the 2nd image, though. This should be pretty simple, but I ´ve got no clue where the error is, so thanks in advance to anyone bothering to look at this.
<?php
$index = 0
$html = file_get_contents("http://www.9gag.com");
preg_match_all( '|http://d24w6bsrhbeh9d\.cloudfront\.net/photo/.+?\.jpg|', $html, $gags);
?>
<script>
function nextImg(){
<?php $index++;?>
pic.src='<?php echo $gags[0][$index];?>';
}
function prevImg(){
<?php $index--;?>
pic.src='<?php echo $gags[0][$index];?>';
}
</script>
You can't increment your PHP variables after the page has loaded. You are trying to increment them client-side with JavaScript. You are going to need to call that PHP using AJAX if you want to do this without refreshing the page, and even then you'll want to increment a javascript variable to keep track of where you are.
EDIT: I went a little nuts creating an ajax routine using PHP and JavaScript, specifically the jQuery library, which you will need to link to for this to work. You may also need to modify parts of the script to work with what you're trying to accomplish, but this certainly is a guide for running your ajax app as you're hoping to.
Start by making a PHP file with this script:
<?php
// Set content header to json
header('Content-Type: application/json');
// Get the index from the AJAX
$index = $_GET['index'];
// Grab file contents & parse
$html = file_get_contents("http://www.9gag.com");
preg_match_all( '|http://d24w6bsrhbeh9d\.cloudfront\.net/photo/.+?\.jpg|', $html, $gags);
// Send filename back to AJAX script as JSON
echo json_encode(array($gags[0][$index]));
?>
Then, in your HTML, include this jQuery to complete AJAX calls to your PHP script, and update the DOM with the data from the PHP script.
<script>
$(function() {
'use strict';
// Initiate index variable
var index = 0;
// Load initial image
loadImage(index);
// Add click event to a button with class of next-btn
$('.next-btn').click(function(e) {
e.preventDefault();
// Increment index to get next image
index++;
// Run AJAX function to retrieve image
loadImage(index);
});
// Add click event to a button with class prev-btn
$('.prev-btn').click(function(e) {
e.preventDefault();
// Decrement the index if it isn't 0
if (index > 0) {
index--;
}
// Run AJAX function to retrieve image
loadImage(index);
});
});
function loadImage(index) {
'use strict';
$.ajax({
type: 'GET',
url: 'your-php-script.php', // Filepath to your PHP script
data: 'index='+index, // Index is passed through GET request
dataType: 'json', // Return JSON
success: function (data) { // If the php script succeeds
// Change img with class of pic's src
// to the filename retrieved from php
$('.pic').attr('src', data[0]);
}
});
}
</script>
Configuring this for your needs will require some serious PHP and jQuery/JavaScript knowledge, as some debugging will likely be needed. Good luck!
EDIT 2:
I uploaded the working (tested, it works) source files to my website if you want to download. Please accept answer and let me know you grabbed the files...
http://www.wedgewebdesign.com/files/ajax-image-loader.zip
#Eric basically has it right but didn't really go into detail if you aren't familiar with the model...
PHP is a server side language in that it does all its processing on the web host server and once it is complete sends a static result back to the user. This means, whatever you see after the page is loaded within PHP is there to stay, unless you do one of two things:
1) Send a new request -- You provide different parameters, the page re-executes its logic and returns a new result to the user
2) Execute some form of clientside Javascript. Javascript is different from PHP in that it executes on the client (not the server) so you don't necessarily have to send responses back to the server unless you need more information. Javascript and PHP can be combined to create AJAX calls which allow the client to make asynchronous calls to the webserver for more data without reloading the entire page. The Javascript handles re-drawing the new information or updating the page which can appear seamless to the user.
What you therefore need is one of those two options. Either you provide 'next'/'previous' links to the user and the page is loaded differently each time or you create an AJAX call that fetches the url of the next image and then loads it.
Try assigning a variable to $gags[0][$index]. Something like
$imgsrc = $gags[0][$index];
and then
pic.src='<?php echo $imgsrc; ?>';

On pressing a link to display a javascript alert box

display a javascript message before proceeding
Continuing from that thread, I would like to know if there is any way I can execute a php source code to display some related data from the database once the ajax get function gets the data of '1'
That is
$.get("display.php",function(data)
{
if(data!='1')
{
if(confirm("Display this item"))
{
// use this place to execute a php file. But how ?
}
}
}
);
You can't execute a PHP file in JavaScript. At that point you will need to use ajax to get whatever content the PHP script you which to execute produces and then use JavaScript to place it on the page (or do whatever else it says to do).
You can perform another ajax request (using $.get again, in your case)
if(confirm("Display this item")) {
$.get("file.php", function(data) {
// Handle data
});
}
call the ajax function again to get data from the php file.

How to make PHP function run after javascript ends?

I have two PHP functions - one that builds a html form and another that handles it when it's submitted.
I want to add to the html a javascript onClick function that sends one of the form's fields to an external API (Google Maps) and saves the reply in a hidden field in the form so that the handling PHP function will get that data as well.
My question is - how do I make sure the handling PHP function only fires after the onClick function has finished?
Or maybe I can't and I have to use ajax?
You'll need 2 events to accomplish this.
the onClick event for your button that executes the google map request and saves the data into the local form
an onSubmit event for your form. You will use this event to see if the form is submittable. Basically, check to make sure that your google map request has been run and has completed before allowing the form to submit.
Example:
<script>
var googleMapsDone = false;
$('#gmap_button').click(function(event)
{
doGoogleMapThing(function()//callback from googlemaps
{
//save data to local form for processing by script once posted
googleMapsDone = true;
});
});
$('#form').submit(function(event)
{
//check to see if we did our google maps stuff, and that its done
if (false == googleMapsDone)
{
event.preventDefault();
return false;
}
});
</script>
With that code, any time the user is waiting for google maps and clicks submit, nothing will happen. They would have to wait on the response from GMaps, THEN click submit. This is okay for some things, but if you're trying to do background requests to GMaps that require no user input/interaction/feedback (maybe getting Long/Lat of their address when they submit a form), then you can modify the code a bit to post when you get the response. An example of that would be:
<script>
var googleMapsDone = false, submitWaiting = false;
$('#gmap_button').click(function(event)
{
doGoogleMapThing(function()//callback from googlemaps
{
//save data to local form for processing by script once posted
googleMapsDone = true;
/* check to see if submitWaiting is TRUE. If it is, automatically
post the form when we get the response.
*/
if (submitWaiting)
{
$('#form').submit();
}
});
});
$('#form').submit(function(event)
{
//check to see if we did our google maps stuff, and that its done
if (false == googleMapsDone)
{
event.preventDefault();
/* set our submitWaiting flag which we will use in our clalback
so when we get our google maps response, we post our form right
away
*/
submitWaiting = true;
/* You might want to display a modal or some other kind of notification
that the form post is 'working' or 'processing' so when the user
clicks it and doesn't see anything happening, they don't bail
or click it 800 times out of frustration
*/
return false;
}
});
</script>
edit: I realize my comment below on how this works are...hard to understand, so let me explain here, then show an alternative.
User fills out form
User clicks button to do stuff on google maps (example was written before I knew the scope/context of the GMaps request, so that's why it's done this way)
If user then clicks 'submit' before the GMap request is complete, we CANCEL the submit and set a flag submitWaiting
GMaps request returns, and executes our callback. Our callback knows how to look for submitWaiting and if it is set to true it submits the form
An alternative to this, instead of requiring user interaction for the GMaps request you could change the event to an onChange event for the input box of the address, or you can do it all via the submit button/event, like so:
<script>
$('#form').submit(function(event)
{
//lets look up our user's address!
doGoogleMapThing(function()//callback from googlemaps
{
//do stuff with your inputs, or whatever
$('#form').submit();
});
event.preventDefault();
return false;
});
</script>
edit note: the examples above assumes you're using jquery, and that your google map API request is done via javascript
If your google map api request is not using the google maps javascript library, this is STILL possible, just requires you to make a "proxy" script to the API via a php script on your local domain. (Browser restrictions). It'd be something like THIS:
<script>
function doGoogleMapThing(callback_when_done)
{
$.post("/path/to/proxy/script.php", { data: to, post: to_server }, function(response)
{
//check & parse response
callback_when_done(/* Data needed to populate form */);
});
}
</script>
note: both of these examples assume jquery usage. because...well..why wouldn't you.
Below is an implementation of your exact script. I changed it a bit to use jquery, because it makes things a bit less painful.
<script type=”text/javascript”
src=”http://maps.google.com/maps/api/js?sensor=false”></script>
<script type="text/javascript"
src="http://code.jquery.com/jquery-1.6.min.js"></script>
<script type=”text/javascript”>
function codeAddress(callback)
{
var address = $('#address').val();
geocoder.geocode( { 'address': address}, function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
$('#latitude').val( results[0].geometry.location.latitude );
$('#longitude').val( results[0].geometry.location.longitude );
if (typeof callback != 'undefined') //call the callback.
{
callback(true);
}
}
});
/* Just in case google returns a bad response or doesn't return at all
we need to add a timeout that will call the callback after 10 seconds
just so we make sure our user doesn't hang.
*/
setTimeout(function(){
callback(false); //pass false indicating no/invalid response
}, 10000); //10000ms = 10s
}
/* We are using the reallySubmit variable as a flag here, to know when we finish
our call to google maps and that we want to really submit our form.
we have to do this because the form.submit() call fires the form's submit event
again, and we end up going into an infinite loop.
an alternative to this would be to bind your form processing to the form's submit
button's click event. that should also pick up any presses of the enter key, also.
the solution below also works.
*/
var reallySubmit = false;
$('#form').submit(function(event)
{
if (false == reallySubmit)
{
//lets look up our user's address!
codeAddress(function(success)//callback from googlemaps
{
reallySubmit = true;
$('#form').submit();
});
event.preventDefault();
return false;
}
});
</script>
This is fundamentally impossible - PHP runs on the server, JavaScript runs on the client. You will indeed need to use Ajax.
You can have a hidden IFRAME element where you load a php document as soon as your javascript ends. Simple, but effective (as long as your php document comes from the same URL).
AJAX is a must I am afraid. You need to redirect the user to a page with the script.
Once the server has run the PHP to generate the HTML, then sent it to the browser, there is no way to run it again, or indeed run anything from the server, without making a request to the server. That is the nature of a server side scripting language, of which PHP is.

Evaluating Returned Data after AJAX call with JQuery/CodeIgniter

EDIT:
I found the problem with my evaluation not working. All the text being returned from my codeIgniter functions has a space before it, so while I saw "success" it was actually " success". I don't know why it is, but I can certainly work with that.
As for the next step - opening a new view - Donny's answer was perfect!
I am using CodeIgniter for an application with JQuery for my AJAX library. I'm just learning the AJAX stuff, so I'm probably missing something basic here...
The following code if for a login form.
The goal is this -use an ajax call on the form submit so I can validate the errors and provide error messages on screen without web page refreshes. I'm doing all my validation with the CodeIgniter form_validation class.
My codeigniter function returns a text value - either an appropriate error message or the word "success." I want to evaluate the text value, and if it says "success", call another ajax function to load the needed CodeIgniter function that will load home page for logged in users.
Right now everything works in the code below until I get to the statement "if data=='success'".
Why would that return false when I know it is true because the on screen message displays "success"?
$(document).ready(function() {
$('#registration_form').submit(function(e) {
e.preventDefault();
$.post("login", {
email : $('#email').val(),
password : $('#password').val()
}, function(data) {
$('#message').text(data);
if (data == "success") {
alert(data);
post("landingpage");
}
});
});
});
You should consider using jQuery form plugins to do form submit using AJAX.
To do redirection, use this code:
window.top.location.assign(URL);
URL is the page destination. If you use CI, you can put this in view:
window.top.location.assign("<?php echo site_url(THE_PAGE_URL); ");
also, you can examine the data value in the Firebug net tab, or in Web Inspector Resource tab (Safari and Google Chrome).

Categories