On pressing a link to display a javascript alert box - php

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.

Related

PHP return partial script

I am creating a php (let's call it pageX.php) file that produces some html. The html has a button that when you press it, I would like to send an AJAX request.
To avoid having multiple files, I want to send the AJAX request to the same file. (pageX.php)
I don't want the AJAX response to return the entire php generated response that it would have with a normal GET request to pageX.php. So I am looking for a php method to simply stop executing and return what it currently has.
I understand I can do this with a big if statement, but I don't like wrapping the bottom part of my code with all the braces. So I am almost looking for the equivelent of a "break" statement for php that will simply return the current php generated html.
Is that possible?
Send your ajax request to pageX.php?ajax=y now you can do this
<?php
if(!empty($_GET['ajax'])) {
//return ajax data
exit;
}
?>
//your Normal html code here

Execute php from javascript

I'm having some trouble getting some php code working in my app.
The setup is rather easy: 1 button, 1 function and 1 php file.
script.js
$(document).ready(function ()
{
$("#btnTestConnectie").click(testConnectie);
});
function testConnectie()
{
$.get("script/SQL/testConnection.php");
}
testConnection.php
<?php
echo "It works!";
php?>
According to this post, it should work (How do I run PHP code when a user clicks on a link?)
Some sources claim that it is impossible to execute php via javascript, so I don't know what to believe.
If I'm wrong, can somebody point me to a method that does work (to connect from a javascript/jQuery script to a mySQL database)?
Thanks!
$.get('script/SQL/testConnection.php', function(data) {
alert(data)
});
You need to process Ajax result
You need to do something with the response that your php script is echoing out.
$.get("script/SQL/testConnection.php", function(data){
alert(data);
});
If you are using chrome of firefox you can bring up the console, enable xhr request logging and view the raw headers and responses.
Javascript is run by the browser (client) and php is run on the remote server so you cannot just run php code from js. However, you can call server to run it for you and give the result back without reloading of the page. Such approach is called AJAX - read about it for a while.
I see you are using jQuery - it has pretty nice API for such calls. It is documented: here
In your case the js should be rather like:
$(document).ready(function ()
{
$("#btnTestConnectie").click($.ajax({
url: '/testConnection.php',
success: function(data) {
//do something
}
}));
});
[EDIT]
Let's say you have simple script on the server that serves data from database based on id given in GET (like www.example.com/userInfo.php?id=1). In the easiest approach server will run userInfo.php script and pass superglobal array $_GET with key id ($_GET['id']=1 to be exact). In a normal call you would prepare some query, render some html and echo it so that the browser could display a new page.
In AJAX call it's pretty much the same: server gets some call, runs a script and return it's result. All the difference is that the browser does not reload page but pass this response to the javascript function and let you do whatever you want with it. Usually you'll probably send only a data encoded (I prefer JSON) and render some proper html on the client side.
You may have a look on the load() of jQuery http://api.jquery.com/load/
You should place all of your functions in the document ready handler:
$(document).ready(function(){
function testConnectie() {
$.get("script/SQL/testConnection.php");
}
$("#btnTestConnectie").click(function(e) {
e.preventDefault();
testConnectie();
});
});
You will have to have your browser's console open to see the result as a response from the server. Please make sure that you change the closing PHP bracket to ?> in testConnection.php.
One other note, if you're testing AJAX functions you must test them on a webserver. Otherwise you may not get any result or the results may not be what you expect.

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; ?>';

How to send data to a php script page during jQuery load and accept the data

I have a php function that builds a list of items for me. Im not sure but i read that you cant call a php function explicitly though jQuery/js.
So i saw that you can still call php pages like this:
$("#name").click(function(){
$("#div").load("script.php");
});
If i can call a php page like that, is there also a way to send it a URL when that page is loaded like this?
$("#name").click(function(){
$("#div").load("script.php", 'http://gdata.youtube.com/feeds/');
});
also another problem comes up that how do i make the script accept that string through from jQuery?
normally when you call a function you pass parameter with the call like so:
<?php makeList( 'http://gdata.youtube.com/feeds/' ); ?>
//on the function-side
<?php
function makeList( $feedURL )
{
//...stuff that uses $feedURL...
}
?>
Since i will make the function a script that runs upon being called how would i pass it a parameter?
I have no idea if this is possible or not and i would understand if this creates tons of security issues which makes it not acceptable.
You have the $.get and $.post methods in jQuery.
$.post('script.php', { url: 'http://gdata.youtube.com/feeds/' }, function(data) {
//data will hold the output of your script.php
});
The url is posted to your PHP script and you can access it through $_POST['url'].
See jQuery.ajax(), the 'sending data to the server' example.

How to check data server side before opening a javascript window

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

Categories