I'm trying to display html form with specific information based on the article id using modal window but I'm struggling to pass value/id to my custom php function.
So, here's the html/php part
while(...) :
Edit
endwhile;
Now js,
$("a.button").on("click", function() {
$("#modal").reveal();
return false;
});
html and php function
<div id="modal">
<?php echo showForm($needThisIDbasedOnClick); ?>
</div>
Hope all this makes sense for you, I'm struggling of getting the certain id and passing to php function
I tried removing the return false; and following the href attribute <a href="?id=17"> ... and than getting the value using $_GET['id'] showForm($_GET['id']) but this solution just don't work the way I wanted, it reloads the page ...
The page with you PHP code is execute on the server side. PHP is interpreted, and then the content is sent to your browser. After receiving the data, your JS code is executed on the client side (thanks to you JS machine of your browser).
If you want to show information without reloading anything, you have 2 solutions:
Embedding all information in the page during the PHP processing and keep it hidden, showing the good one with JS code depend on the link clicked. (Bad solution)
Use an AJAX request with the ID in parameter that will call to a new short PHP script returning the information of the specified row.
If I resume the process could be:
1) The first request is on your main script main.php
2) The page display all your item (embedding only the ID) and contain the information container (which is hidden and empty)
example
<!-- Your list of link with article ID -->
<div>
<a class="articleLink" id="123" href="#">View</a>
<a class="articleLink" id="124" href="#">View</a>
<a class="articleLink" id="125" href="#">View</a>
</div>
<!-- The bloc that will contain info and will be shown in a popup later (hidden) -->
<div id="divInfo">
<input type="text" name="name" value=""/>
<input type="text" name="description" value=""/>
</div>
<script>
$(document).ready(function() {
// add listener to all link
$(".articleLink").click(function(mouseEvent) {
// Retrieve the article ID
var myId = $(this).attr('id');
// Ajax call with the id of the link
// onSuccess, fill the divInfo and show it
$.ajax('getInfo.php', {
dataType: 'json',
type: 'POST',
data: {
articleId: myId
},
success: function(data, status, xhrObj) {
// The data is received, update the info container
$("#divInfo input[name=name]").val(data.name);
$("#divInfo input[name=description]").val(data.desc);
// Show the div in a popup
//...
}
});
return false;
});
});
</script>
3) You are clicking on one link, it will run an ajax call to a second PHP script : getInfo.php, giving the specified ID
4) The script retrieve data in your Database and finally return the information (in JSON for example)
Assuming your PHP getInfo.php will return JSON like
{"name":"an article name","description":"the article description"}
Note: you can produce easily JSON in PHP from array with the function
json_encode()
5) the method onSuccess of your Ajax call is called when the data is received, and you can use the data to fill your form (which is unique and already present in the page - and is hidden).
good luck
Related
I am complete php/js newbie and i got stuck on something that i cant figure out.
I have page at www.test.com/page with a search form that calls www.test.com/results like this:
<form method="post" action="https://www.test.com/results">
<input type="text" placeholder="Enter URL:" required="">
<button>Search</button>
</form>
Form gets URL that the user typed in, passes it to /results, the line ($url = $_POST['url'];) is where it is analyzed and results are displayed.
But, i would want the search results to open in (bootstrap) modal instead of new page. I know this can be done with AJAX but i am complete newbie and am looking for most dirty simple solution that would make it work.
Again, sorry if this is too "newbie" type of question, i am still learning.
Yes, you can use jQuery and AJAX to control the form submit. So something akin to the code example below should do the trick:
$('#myForm').on('submit', function(event) {
$.post('https://www.test.com/results', { URL: "some_url.com" }, function(data) {
// Render the results onto your modal anyway you want with data
// retrieved from server here
$("#my-modal-object").html(data);
}).error(function() {
// Handle the event when the call to "/results" fails
alert("Yikes! Call to /results failed!");
});
// Prevents default browser behaviour which submits the form
// then routes to another page, if specified
event.preventDefault();
});
Short explanation:
We attached a "submit" event listener to your form object and performed a POST AJAX request to your server endpoint /results. Server passes back the processed search results into the callback function of $.post and renders it onto your modal object. You may also change the 2nd argument of $.post, i.e. { URL: "some_url.com" } to whatever data object you want to pass to your server.
This should help you get started with rendering your search results onto your modal element instead of navigating to a new page.
I'm trying to figure out a way to load 1 single tab(tabs by jQuery) without reloading all the others.
The issue is that I have a submit button and a dropdown that will create a new form, and when on this new form 'OK' or 'CANCEL' is clicked, it has to get the original form back.
The code to load a part of the page that I found is this:
$("#tab-X").load("manageTab.php #tab-X");
But now I would like to know how to use this in combination with the $_POST variable and the submit-button
Clarification:
I have a .php(manageTab.php) which contains the several tabs and their contents
I have in each of these tabs a dropdown containing database-stored information(code for these dropdowns is stored in other pages)
for each of these dropdowns, there exists a submit button to get aditional information out of the DB based on the selection, and put these informations in a new form for editing
this new form would ideally be able to be submitted without reloading everything except the owning tab.
Greetings
<script>
$(document).ready(function() {
$("#form1").submit(function(){
event.preventDefault();
$.post('data.php',{data : 'dummy text'},function(result){
$("#tab-X").html(result);
});
});
});
</script>
<form id="form1">
<input id="btn" type="submit">
</form>
I am not totally understand your question, but as per my understanding you can't load one tab with form submit. Its normally load whole page.
What you can do is, use ajax form submit and load the html content as per the given sample code.
$.ajax({
url: url, // action url
type:'POST', // method
data: {data:data}, // data you need to post
success: function(data) {
$("#tab_content_area").html(data); // load the response data
}
});
You can pass the html content from the php function (just need to echo the content).
AJAX is what you are looking for.
jQuery Ajax POST example with PHP
Also find more examples about ajax on google.
Example: Let me assume you have a select menu to be loaded in the tab.
You will need to send a request to your .php file using jquery, and your php file should echo your select menu.
In your jQuery,
<script>
$.post(url, { variable1:variable1, variable2:variable2 }, function(data){
$("#tab-X").html(data);
//data is whatever php file returned.
});
});
$("#form_id").submit(function(){
return false;
});
</script>
I mean whatever your options are, you will need to do the following in your .php file,
Echo that html code in your PHP script.
echo "<select name='".$selector."'>
<option value='".$option1."'>Option1</option>
<option value='".$option2."'>Option2</option>
<option value='".$option3."'>Option3</option>
</select>";
This would be returned to jQuery, which you may then append wherever you want.
Do you know a way to display a php result inside a div dynamically, without refreshing the page?
For example, we have 2 divs: one on the top half of the page and one on the bottom of the page. The top one contains a form with 3 input fields. You type some values inside, then press a button. When you press the button, the bottom div displays the values without refreshing the page.
You can't do it with pure PHP because PHP is a static language. You have to use Javascript and AJAX. I recommend using a library like Zepto or jQuery to make it easy to implement like this:
<form>
<input name="search" />
<input type="submit" />
</form>
<div id="div2"></div>
<script>
// When the form is submitted run this JS code
$('form').submit(function(e) {
// Post the form data to page.php
$.post('page.php', $(this).serialize(), function(resp) {
// Set the response data into the #div2
$('#div2').html(resp);
});
// Cancel the actual form post so the page doesn't refresh
e.preventDefault();
return false;
});
</script>
You can accomplish it using AJAX. With Ajax you can exchange data with a server, make asynchronous request without refreshing the page.
Check this out to see how it can be implemented using Jquery:- http://api.jquery.com/jQuery.ajax/
I am working with a mobile application in which
first page has
Html
<ul>
<li>121212</li>
<li>123233</li>
<li>232323</li>
<li>4323423</li>
<ul>
when user click on "li" then he/she entered on next page which will retrieve data related to selected "li" via Ajax.
this is almost going good..
But when Ajax response come page is fluctuating 2 times.
Means one time page loading, next time page totally white and then again showing page with Ajax response.
Why ???
J query
$("clickOnLi").click(function(){
var id= $(this).val(); //get the selected li value
$('.loadingGif').css({ 'display':'block' });
$("#ulShowContent").html(''); // to remove old inner HTML to show new result html
var dataString = 'selectedid='+id;
$.ajax({
type: "POST",
url: remoteUrl+"handler.php",
data : dataString,
cache: true,
success: function(response) {
if(response){
$('.loadingGif').css({ 'display':'none' });
$("#ulShowContent").html(response);
}
}
});
})
**and the result will show in this html**
<ul id="ulShowContent" data-role="listview">
<li class="comment chatsend">
<div class="comment-meta">
data 1
</div>
</li>
<li class="comment chatsend">
<div class="comment-meta">
data 2
</div>
</li>
</ul>
You will need to change how you deal a page change and AJAX call.
What I have understand from your question, after click on LI element, page change is initialized and AJAX call is sent to a PHP server.
You will need to change this logic. Page fluctuations are cause by AJAX call which is executed during the transition from one page to an another.
This can be fixed like this:
On a first page remove HREF attribute from a list element
Add a click event to every list element
AJAX call should be executed on click event, at a same time show your custom loader (or use a default one)
When server side data is retrieved you need to store it so it can be accessed from an another page. Here you will find my other ANSWER where you can find various methods of storing data during page transitions, or find it HERE, just search for a chapter called: Data/Parameters manipulation between page transitions (your best bet is a localstorage).
Initialize a page change with changePage function
During a pagebeforeshow event (page is not yet displayed) append new data to the new container
When second page is finally shown everything will be there and
I am creating a PHP site and have ran into the following problem, i would like to be able to click a hyperlink on a page, send a small data item to a php script, have the script perform its function and then return the results.
I am using AJAX with this site to have each page load into a div section of the site, all pages, data and responses load into this central div, like so:
<html>
<body>
<div id="topMenuBar">
<div id="contents">
//ALL DATA IS LOADED HERE...//
</div>
</div>
</body>
</html>
So, when a page is selected from the top menu i simply have the following code run:
$('#topMenuBar a').click(function(e)
{
e.preventDefault();
$('#contents').load($(this).attr('href'), function()
{
});
});
Now that pages load into the content section, I am loading a page called "results.php" which connects to a DB, queries it, and the creates a HTML table with the results. Each table row has a small hyperlink which when clicked is intended to send a value to another PHP script and then clear the contents div and then repopulate the div with the response from this script (getInfo.php). For example, a row will have the following PHP code generate a link:
<label class="moreInfo"><a name="test01" onClick="getInfoFromPHP(<?php echo $data[$id]; ?> )">Get Info</a></label>
So when the table is generated by PHP it, the link when clicked passes a JS function the value.
What i now need to do is to send the value to a PHP script which will again query the DB, and have the results inserted into the "contents" div. I have been trying the following function.
function getInfoFromPHP(myVar){
var netID = myVar;
$.ajax({
url: "getInfo.php",
type: "POST",
data: {
networkID: netID
},
success: function(html) {
$('#contents').empty();
$('#contents').load(html);
}
});
};
When i call the function it does seem to send the data to the script but i get the following error from firebug:
POST http://127.0.0.1/private/networks/includes/leave_a_network.php - 200 OK -15ms
GET http://127.0.0.1/%3Ch2%3EHello 403 Forbidden 21ms
"NetworkError: 403 Forbidden - http://127.0.0.1/%3Ch2%3EHello" Hello
The PHP script is only doing the following:
<?php
session_start();
$networkID = $_POST['networkID'];
echo "<h2>Hello World</h2>";
?>
What is the best way to send data to a PHP script and have it load into a div?
Thanks for any feedback.
In the success function, put $('#contents').html(html); instead of load.
success: function(html) {
Is returning html as a string that does not need to be 'load'ed again like you try here -
$('#contents').load(html);
Change that line to this
$('#contents').html(html);
A better way is using $.ajax to send the request. On the success callback, you can analyse the result, and do what you want with :
http://api.jquery.com/jQuery.ajax/