Call PHP file without using form action - javascript

I am new to php. I did a little search but did not find a good solution. So posting the question here.
I have several thumbnail images in my webpage. Something like:
<img src="" id="thumb1">
<img src="" id="thumb2">
<img src="" id="thumb3">
<img src="" id="thumb4">
I want to call load a php file when a user clicks on any of these thumbnail images and pass the id of the image to the php file. This php file queries the database with the image id and displays the relevant information. So far I used "form action" to call a php file.
Can you please tell me how to call php file and pass the image id?
Thanks.

Use links:
<img src="" id="thumb1">
<a href="php_file.php?id=thumb2"><img src="" id="thumb2">/a>
<a href="php_file.php?id=thumb3"><img src="" id="thumb3">/a>
<a href="php_file.php?id=thumb4"><img src="" id="thumb4">/a>
php side: $_GET['id'];

You can post to a script without using a form, here is a simple example
$.post("get_image.php", { thumbId: thumb1 }, function(response) {
console.log(response);
});
And in php side $_POST['thumbId']

If you are using jQuery try this:
var get_thumb_details = function(thumb_id) {
$.ajax({
type: "POST",
url: "process_image.php",
data: {
thumb_id: thumb_id
}
})
.done(function( data) {
// This is the data received from the server
console.log(data);
});
};
// Attach onclick event on your images
$('img').on('click', function() {
var thumb_id = $(this).attr('id');
get_image_details(thumb_id);
});
On the server side you can access the request parameters using the $_POST object.
$input_thumb_id = $_POST['thumb_id'];
var_dump($input_thumb_id); // if you want to check the variable value

You can try Angualr Js. In angular js we can the get the form elements attributes without submitting. So you can get the image id's on clicking using angular js. You can pass the same to get your required php page.

Related

How to include PHP file with JavaScript and pass parameters

I need to run a PHP function in a page, after the user clicks on something, in this case, a link.
First I was using onclick to run a javascript AJAX to request a PHP file with the function in it. The thing is, I need to pass a parameter to the function, and I can't seem to be able to do it with AJAX.
If it was a PHP include, it would behave like it 'appended' the other file to the current file, so this way, the included file could reference variables in the current file. Apparently, AJAX is just taking the file I need, running it's code, and displaying the results. So yeah, doesn't work for me.
So basically. I need an exact replica of PHP's 'include', on JavaScript.
OR any other workaround.
My current code:
<br> <div id="seeMore"> </div> <br>
<ul> <li style="float: left"> Ver Mais </li> </ul>
<script type="text/javascript">
function loadMore()
{ $("#seeMore").load("feedP.php"); }
</script>
This is the part of the code in the main page that im needing help with, you can see it's loading a page called feedP.php, here's it's code:
<?php
echo 'test';
require_once('functions.php'); loadFeeds($urls, 5);
?>
As you can see, I have to run a function called loadFeeds, and it requires a parameter, $urls. Witch is created back on the main page.
EDIT:
I CAN'T reload the page, or redirect the user, that's why i'm trying to 'append' the file here.
You can use the second parameter of the load function which takes parameters that can be posted to the file in question:
$("#seeMore").load("feedP.php", {
url: 'url'
});
Then, in your PHP you can make use of $_POST to access the posted data.
data
Type: PlainObject or String
A plain object or string that is sent to the server with the request.
Reading Material
.load
You can pass the parameters through load function. I have altered your script code as below.
<script type="text/javascript">
function loadMore() {
$("#seeMore").load("feedP.php", {urls: "<?php echo $url; ?>"});
}
</script>
In the above code $url is the php variable which you assign the url you need to pass to feedp.php

Display PHP var in HTML (with jQuery)

I'm searching for the best solution to display information which I store in PHP variable (which I get from a MySQL DB).
I was thinking to use jQuery. My questions:
With the input field I receive the number of the Member.
I store a new variable called $imgMember with the img name.
Questions:
I want to display this image each time a user enters a number at <div class="boxImageMember"> (which I already validated through PHP and made a variable ($imgMember) of it.
How should I access it? Do I need to store those variable with AJAX? Internal/external jQuery? Or do I need to think otherwise? Im stuck in my head.
Im totally stuck with the way I how to process this.
HTML:
<div id="header">
<div class="header-content">
<img src="img/logo-dqmih.png" width="60px">
</div>
</div>
<div class="container">
<div class="boxImageMember">HERE I WANT TO DISPLAY A USER IMAGE</div>
<div class="boxInformationMember"></div>
<form action="" method="post">
<input type="text" id="MemberNumberEntry" name="staffNumber">
<button type="submit" name="action">
</form>
</div>
jQuery:
$(document).ready(function() {
$("#MemberNumberEntry").focus();
$(document).on('submit',function(event, test){
event.preventDefault(); // Don't refresh the page
var MemberNumberEntry = $("#MemberNumberEntry").val();
console.log(MemberNumberEntry);
$(".boxImageMember" ).css("background-image", "url(../images/persons/NIT.jpg)"); // Change image (Not dynamic yet)
$(".boxInformationMember" ).text("Hi Test, welcome!");
// Reset value form entry
$('#memberNumberEntry').val('');
});
});
Your jQuery script would do something like this
$(document).ready(function() {
$("#MemberNumberEntry").focus();
$(document).on('submit',function(event, test){
event.preventDefault(); // Don't refresh the page
var MemberNumberEntry = $("#MemberNumberEntry").val();
//console.log(MemberNumberEntry);
$.ajax({
url: '/your-php-script.php',
method: 'POST',
data: {
MemberNumberEntry: MemberNumberEntry
},
success: function(response){
//If call goes well, you use the image here.
}
});
$(".boxImageMember" ).css("background-image", "url(../images/persons/NIT.jpg)"); // Change image (Not dynamic yet)
$(".boxInformationMember" ).text("Hi Test, welcome!");
// Reset value form entry
$('#memberNumberEntry').val('');
});
});
You're basically sending an HTTP POST request to your PHP script that will accept the image ID like a normal post request, using $_REQUEST or $_POST.
There are tonnes of options to configure with jQuery, you can look at the docs here. For more information on working with images in PHP and AJAX, this answer is useful.

jquery loading script when preparing document

I have a problem with jquery and would appreciate a help from stackoverflow community to solve following problem
Lets assume that there a server side script which creates doc file and following links calls it
<a class="prepare_doc_file" href="somepage.php?action=docfile">docfile</a>
what i need is jquery script, which shows loading image, when doc file if being prepared (or when the link is clicked) and hide it after getting download popup.
I see loading circle in the tab in browser. I need the same thing inside the html document
Thank you
You need to use AJAX, and generate a tempfile to download.
Your php can generate file and save to some temp path. After downloading you can delete this file.
<a class="prepare_doc_file" id="downloadfile" href="somepage.php?action=docfile">docfile</a>
function loadFile(){
document.getElementById('downloadfile').innerHTML='loading, please wait';
$.ajax({
url: 'somepage.php?action=docfile',
complete: function (data) {
document.getElementById('downloadfile').href='path to file'; //path may be returned on php.
document.getElementById('downloadfile').innerHTML='docfile';
}
});
}
<div id="myDiv">
<img src="loading gif image url">
</div>
<script>
$.ajax({
type: "POST",
url: "url to the page where the contnt is",
data: 'parameters if any' ,
success: function(result){
//logics
$("#myDiv").html("<a class="prepare_doc_file" href="somepage.php?action=docfile">docfile</a>");
});
</script>

How do I use ajax to upload a text field and a file?

I'm new at AJAX and am working on an implementation of a form that will upload a name and a file to a php file that processes the data and sends it to a database for insertion using mysqli. I've tested the php file and it does work. My problem is in the AJAX code. I've tried an implementation using XMLHTTP and using jQuery. Both leave the page and open the PHP file in the browser. As a disclamer, I posted this question to another coding site, a fight ensued between two posters, and so I'm trying here to hopefully get a reasoned and calm response with productive suggestions.
I realize that currently "get" is being sent to the PHP file rather than "post", but PHPStorm tells me that "post" is not available in that form. What's my alternative? Am I on the right track or is there another direction I should go? How do I refresh only the form and keep the PHP page from loading?
Here's the relevant snippet of my code,
<!DOCTYPE html>
<html>
<head>
<script src="jquery.min.js"></script>
<script src="jquery.validate.js"></script>
<script>
$(document).ready(function() {
$('#addForm').validate({
submitHandler: function (form) {
$('input[name="usingAJAX"]', this).val('true');
var url = $(form).prop('action');
var dataToSend = $(form).serialize();
var callback = function(dataReceived) {
$(form).hide();
//result message
$('body').append(dataReceived)
};
var typeOfDataToReceive = 'html';
$.get(url, dataToSend, callback, typeOfDataToReceive),
return false;
}
});
});
</script>
</head>
<body>
<form id="addForm" action="addInfo.php" enctype="multipart/form-data">
<input type="hidden" name="usingAJAX" value="false"/>
<label for="aname">Name: </label>
<input type="text" name="aname" id="aname" class=required/>
<label for="aimage">Photo: </label>
<input id="aimage" type="file" name="aimage" class="required">
<input type="submit" value="ADD"/>
</form>
</body>
</html>
Until recently you could not upload files with ajax.
You still cannot upload the file directly with ajax, but you can do it programatically with HTML5 File API.
Still, if you are looking for simple solutions, try traditional IFrame approach.
If you want bleading edge technology, use File API. Here is some tutorial how to read files with javascript.
The steps to upload with ajax:
Read file with javascript FileReader API.
Post the content of the file, encoded to base64 or something, to the server.
Serverside, decode the contents of the file programatically.
When using this approach, the file will not be handled as a file upload by the server. It will be just another request field with text inside. It is up to you to decode it on the server side.
The filereader API allows you to read the file portion by portion and upload fragments of file, so it would be possible to upload huge files in chunks, but you need to handle it yourself.
Try using plugin jQuery form.js http://www.malsup.com/jquery/form/#file-upload You can upload files with ajax and jQuery. It is easy to use, just need to give #form-id in ajaxSubmit function.
<script>
$(document).ready(function() {
$('#addForm').validate({
submitHandler: function (form) {
$('input[name="usingAJAX"]', this).val('true');
var options = {
url : $(form).prop('action'),
dataToSend : $(form).serialize(),
callback : function(dataReceived) {
$(form).hide();
//result message
$('body').append(dataReceived) },
typeOfDataToReceive = 'html';
//your options here
};
$('#yourFormid').ajaxSubmit(options);
return false;
}
});
});
</script>

deferring JavaScript execution in document received via AJAX

I'm receiving this HTML document via AJAX:
<form enctype="multipart/form-data" method="POST" action="admin.php?do=media&action=file-upload">
<div id="uploadForm">
<div id="fileList">
</div>
[Select File]
[Start Upload]
</div>
</form>
<script type="text/javascript">
// $(function(){}); not working when data loaded with ajax request
var ajaxUpload = new plupload.Uploader({
runtimes: 'gears, html5, flash',
url: 'upload.php',
browse_button: 'selectFile',
});
ajaxUpload.bind('Init',function(param){
console.log(param);
console.log($('selectFile'));
});
$('#uploadFile').click(function(){
alert('Something');
});
ajaxUpload.init();
</script>
When I append this to the main document, the JavaScript inside it will immediately run and not be able to find the referenced DOM elements.
It works when I add a time-out on the code, but I would like to know a better way at achieving this.
Update
Modified to reflect the true intent of the question.
This is not possible in the manner which you've described, because the JavaScript is not bound to a condition to run, so it runs immediately.
The code inside the document you're receiving via AJAX should be wrapped inside a function by providing side:
function onDocumentReady()
{
// your code here
}
Then from the loading code:
// get the HTML and JavaScript in data
$('#container').append($(data));
// fire the function to let JavaScript run
onDocumentReady();
If you have multiple requests, the providing side should make the onDocumentReady function unique by adding random alphabets to the function name, e.g. onDocumentReady_123()
Wrap your code inside a $(document).ready. This will ensure that your JavaScript doesn't run until the DOM is loaded and the elements you're targeting will be available on the page:
$(document).ready(function() {
var ajaxUpload = new plupload.Uploader({
runtimes: 'gears, html5, flash',
url: 'upload.php',
browse_button: 'selectFile',
});
ajaxUpload.bind('Init',function(param){
console.log(param);
console.log($('selectFile'));
});
$('#uploadFile').click(function(){
alert('Something');
});
ajaxUpload.init();
});
For more information on how this works, see the documentation for jQuery ready. The site also has information on other useful jQuery commands that may be helpful, and I encourage you to check it out and try the examples that are there. Good luck!
UPDATE:
If I understand correctly, you're getting something like this HTML from the server:
<!-- Pulled HTML from the server using AJAX -->
<div id="uploadForm">
<div id="fileList">
</div>
[Select File]
[Start Upload]
</div>
And maybe trying to inject it dynamically into this:
<form action=""> <!-- inject HTML here --> </form>
If my understanding is correct, then this should allow you to inject the HTML and then only run the JavaScript once the AJAX request completes, and the new DOM has been injected. Keep in mind that, since I don't have all of your code, this is just a conceptual example:
$.ajax({ url:"/somepathtoGetData",
success: function(data) {
// your HTML is in the variable "data", and this injects the HTML into
// the form element on the page
$('form').html( data );
// now that the DOM elements are loaded from the AJAX request, do your
// other stuff with the uploader here
var ajaxUpload = new plupload.Uploader({
runtimes: 'gears, html5, flash',
url: 'upload.php',
browse_button: 'selectFile',
});
ajaxUpload.bind('Init',function(param){
console.log(param);
console.log($('#selectFile')); // added # for id attr
});
$('#uploadFile').click(function(){
alert('Something');
});
ajaxUpload.init();
}
});
UPDATE
Say I have two php files, one is main.php, having such codes: (not including jQuery src, please add your own)
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
$('#b').click(function(){
$.post("ajax.php",
{
taskaction: "getFormAndJs"
},
function(data){
$('body').append(data);
// $(document).trigger("ready");
},
"text");
})
});
</script>
<body>
aaaaaaaaaaaaa
<input type=button id="b" value="click" />
</body>
another is ajax.php, like this:
<?php
if ($_POST['taskaction'] == 'getFormAndJs') {
echo '
<div id="uploadForm">222</div> <input type=button id="a" value="upload" />
<script>
$("#a").click(function(){
alert(123);
})
</script>
';
}
?>
It seems work on my side (click button a and alert "123"), whether I add the
$(document).trigger("ready");
or not.
Does this look like your situation?

Categories

Resources