I have a file (lam.php) that displays a database-driven list of countries in Latin America. I would like to include it in various pages on my website as a convenient reference. But rather than simply include it, I'd like to use AJAX, so the users can decide whether or not they want to view the list.
So I'm learning how to work with AJAX. It sounds like I want to use jQuery + AJAX, using Post instead of Get.
But I immediately got hung up on an error on this line:
$.post("http://gx/2b/inc/C/Shared/DBLists/World/lam.php",data,callback);
I don't see any errors displayed when I preview the page, but the error is highlighted in Dreamweaver. Nothing happens when I click the button, so there's obviously an error somewhere. Can anyone spot the error(s) in my script?
This is the entire script:
<head>
<script>
$(document).ready(function(){
$("button#lam").click(function()
$.post("http://gx/2b/inc/C/Shared/DBLists/World/lam.php",data,callback);
)
}
)
</script>
</head>
<body>
<button id="lam">Latin America<button>
</body>
You need to add a DIV to the HTML for the result to be displayed in. Then the callback function has to fill in the DIV with the response from the AJAX call.
Since your PHP script doesn't take any parameters, you don't need the data argument.
<head>
<script>
$(document).ready(function(){
$("button#lam").click(function()
$.post("http://gx/2b/inc/C/Shared/DBLists/World/lam.php", function(response) {
$("#lam-result").html(response);
});
});
});
</script>
</head>
<body>
<button id="lam">Latin America<button>
<div id="lam-result"></div>
</body>
Related
I have a .php file with HTML code and inside it I call another php with html file with AJAX. A form.
Apparently something with this form is wrong, or the query after it. Problem is:
When I submit it, the page reloads, and I cannot debug my form.
When I use preventDefault on my code, and prevent the form from
submitting I cannot debug because the query is not executed yet.
Cannot write an html message displaying the variable because after
reload php with the form is gone.
How can I debug my code in this situation?
File1.php
$(".edit-post").click(function(){
var postid = $(this).attr("id");
$.ajax({
type: "GET",
url: "/admin/EditProductForm.php/",
dataType: "html",
data: {
ajaxpostid: postid
},
success: function(data){
$('#post').html(data);
}
});
$("#post").show();
});
EditProductForm.php
<?php
$ID = $_GET["ajaxpostid"];
$post = GetProduct($ID);
if(!empty($_POST)){
...query
}
?>
<html>
<form>
.
.
.
</form>
</html>
The first thing to understand is that although your HTML and Javascript might have been delivered to the workstation by PHP, it is now running in a totally separate environment with no access to PHP at all.
The PHP you're running on your server is running in the server environment, and has no access to the HTML and JavaScript running in the browser.
The two parts of your application communicate either by sending data as part of a GET or POST request when the form is submitted, or by sending and receiving messages through AJAX. It would be unusual to use both methods in one page.
Thus, you can debug the two parts separately.
Turning to your code:
Your AJAX code is triggered when your button is clicked. In the absence of any other attributes, the button will also trigger a submit. This is what is causing the page to reload. Since you're using AJAX to update your page you don't want it to reload, so stop it with preventDefault();
$(".edit-post").click(function(event){ // add the event parameter here
event.preventDefault(); // Prevent the default action - the submit.
var postid = $(this).attr("id");
...
With this done you can use the browsers tools Network tab to watch the messages, see what's being sent, and look at what response is received.
The server end of things is a little more awkward, but adding echo statements at appropriate places can provide useful output while debugging. Note that you don't need your AJAX script to debug the server end - a simple HTML form with the right fields will do. If you're using GET you could even type the URL and query string on the command line by hand and watch the results.
In your code there is a basic flaw, however.
In your AJAX code you're setting the request type to GET (type: "GET",). In your PHP script you're looking for $_GET["ajaxpostid"];, which is OK, but then you start looking at the $_POST array, which will be empty because your AJAX call used GET.
Now at this point, there's not enough code to be clear about what you're trying to achieve. If your SQL query is just retrieving data to populate an edit form then GET is an appropriate method, and you shouldn't be looking at the $_POST` array.
However, the code you've posted suggests that the EditProductForm.php code is generating the HTML to perform the edit. If this is the case you don't need AJAX at all, and you can just submit the form from File1.php. On the other hand, if you want the page to transform to an editing form without a refresh then File1.php needs to create the editing form and incorporate the data sent by the server, and your EditProductForm.php should not do that job.
a button on form can have three types button|submit|reset , the default type is submit.
on your case, you are clicking on button which has the default type of submit, so its submitting form. that's why the page refreshes. but you want to apply Javascript instead.
so in these cases, either you apply event.preventDefault(); with the javascript code to stop form submission, or simply add type="button" to your button to explicitly say this button is going to run javascript
type=submit -> it means button is going to submit form date
type=reset -> it means button is going to clear form data
type=button -> it means button is going to apply javascript
<button type="button">Submit</button>
file 1(jquery):
$(".edit-post").click(function(){
var postid = $(this).attr("id");
$.ajax({
type: "GET",
url: "./EditProductForm.php",
dataType: "html",
data: {
ajaxpostid: postid
},
success: function(data){
$('#post').html(data);
}
});
$("#post").show();
});
file 2:
<?php
if($_GET["ajaxpostid"] == "test"){
?>
<!DOCTYPE html>
<html lang="fa">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type='text/css' href="../Requirement/css/bootstrap.min.css">
<link rel="stylesheet" type='text/css' href="./index.css">
<title>test</title>
</head>
<body>
<h1>hello world !</h1>
<script src="../Requirement/js/jquery-3.5.1.min.js"></script>
<script src="../Requirement/js/bootstrap.min.js"></script>
<script src="../Requirement/hls.js/dist/hls.min.js"></script>
</body>
</html>
<?php } ?>
I am trying to test the jQuery GET method, but what I am getting as result is completely insane. All I am trying to do is call a function from my controller with jQuery and then display the echoed value in a div within my view. Below is my code and finally a breakdown of the problem I am encountering.
Controller
public function generate_suggestions2() {
echo "James";
}
View views\suggestions_v.php
<body>
//This DIV is used a button to call the jQuery function
<div id="next_btn">
<p>Click here to display a name</p>
</div>
//In this div the value retrieved by the jQuery should be displayed
<div id="listB"></div>
//This is the function that calls the function within my controller
<script type="text/javascript">
$( "#next_btn" ).click(function() {
$.get("core/generate_suggestions2/",
function(data) {
$( "#listB" ).html(data);
});
});
</script> //For some reason I need to put the script at the end of the body. When it's in the head nothing happens when I click the button. Also something I do not understand.
</body>
Now the problem is that when I click the DIV next_btn it does NOT display the James in the DIV listB.
Instead it populates the DIV listB with my source code from my main view views\core_v.php
I have no idea how this is even remotely possible, so please if you have a clue or even better you know what I am doing wrong please tell me. I am trying to get this to work for the past three days without any success or progress :(
Try using this code in your view
<script type="text/javascript">
"$( "#next_btn" ).click(function() {
$.get("<?php echo site_url().'/core/generate_suggestions2';?>",
function(data) {
$( "#listB" ).html(data);
});
});"
</script>
Also delete the </script> tag just right before this block comment.
Regarding this comment you have:
//For some reason I need to put the script at the end of the body. When it's in the head nothing happens when I click the button. Also something I do not understand.
It is because the DOM is not yet fully loaded and Javascript executes its code when the browser has finished loading the DOM you are referring to. So you either have to put it after the DOM element you want to edit, like you do now or you could use $(document).ready(function(){
}
); .
Read more about it here
This line is pretty strange:
</script><script type="text/javascript">
Try to delete first closing tag 'script' on it.
I want to execute a php code when a user click on a given link , i've tried the following code
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
function doSomething() {
$.get("up.php");
return false;
}
</script>
</head>
<body>
<center>
Click Me!
</center>
</body>
</html>
where up.php is a php code that implement android GCM mechanism similer to the one in the link : GCM with PHP (Google Cloud Messaging)
but unfortunately when the link is clicked nothing happens , the php code not executed ,and only the url of the page change form *****.com/test.html to *****.com/test.html# , and by the way I've tested the php code and its works fine so it is not a problem in php code , so what i have missed here? why the code is not executed?
i found the solution , the problem that the jquery library is not included probably in my code
you are using jquery. $.get() will be something like below.
$.get('ajax/test.html', function(data) {
$('.result').html(data);
alert('Load was performed.');
});
for further help check http://api.jquery.com/jQuery.get/
Sometimes, you may need to call some JavaScript from within a link. Normally, when user click on a link, the browser loads a new page (or refreshes the same page).
This might not always be desirable. For example, you might only want to dynamically update a form field when the user clicks a link.
To prevent the load from refreshing, you could use the JavaScript void() function and pass a parameter of 0 (zero) as below.
<a href="JavaScript:void(0);" onclick="return doSomething(); " />Click Me!</a>
Now if you want to use href="#", make sure onclick always contains return false; at the end.
OR
Use href="javascript:void(0)"
You can also use jQuery Load
function doSomething() {
$('#result').load('up.php', function() {
alert('Load was performed.');
});
}
When you are using Jquery should be :
function doSomething(){
$.get('up.php', function(data) {
$('.data').html(data);
});
}
Link
To stop page refreshing, you can use the javascript void() function and pass parameter of 0.
Click Me!
<div class="data"></div>
This div is used to display up.php result.
Ok start of by using fire bug and watch the console and network panels
Ensure the browser is trying to get something and not returning a 404 or a php error on the get
Look into prevent default http://api.jquery.com/event.preventDefault/
To stop the original link functionality working
If you still want them to move to the link use a window location or...
Look into bootstrap link buttons
http://twitter.github.com/bootstrap/base-css.html#buttons
( the link button )
I have recently installed Simple Mailing List 2 (currently in beta) and I have got everything to work so far. The main thing that was left for me to do was to make a custom php page which the signup form redirects to once submitted. The content that the page shows is based on what the user enters in the email field and returns one of three results:
an error message if the email syntax is incorrect.
a custom message if the user has subscribed telling them to check their email.
a custom message if the user has chosen to unsubscribe.
That's the background out of the way. Now what I intend to do is show a popup window that includes the contents of the redirected php page (ie. one of the three results) instead of going to a new page. Is it possible to do this a css popup box so I don't have to open up a new window?
Thankyou
Adam
You can use JavaScript to send an ajax request to the PHP page that will do the calculations, the result will then be sent to your "window" content and then you show the window to the user
You're mixing metaphors. CSS is just a presentational technology that you use to determine the style of something. There is no such thing as a "css popup box".
What you want to do is have an HTML element (likely a div) that contains the information you intend to show, initially set to not be visible (you use CSS for this with the display:none; style). What you're describing is essentially an AJAX interaction that uses Javascript to parse the contents of the form, send data to the server to be evaluated, and return a message to be displayed (without triggering a postback/going to a new page). That Javascript would also handle the CSS part of setting the display of the HTML element to true.
This is a fairly common scenario, so you should be able to find snippets online.
...but here's a super dumb example
<html>
<head>
<title>AJAX Test</title>
</head>
<body>
<form action="#">
<input type="text" id="enterStuff" />
</form>
<div id="response" style="display:none;">
<p id="message">Put stuff in me</p>
</div>
<script type="text/javascript">
jQuery(document).ready(function(){
registerEventListeners();
});
function registerEventListeners(){
jQuery("#enterStuff").change(getData);
}
function getData(){
jQuery.ajax({
type : 'POST',
data : {
stuff : jQuery("#enterStuff").val(),
},
url : "http://localhost/myprocessor.php",
success : showCool,
complete : updateDisplay
});
}
function showCool(data, textStatus, jqXHR){
var selector = jQuery("#message");
selector.val(data)
}
function updateDisplay() {
jQuery("#response").show();
}
</script>
</body>
</html>
Then your myProcessor.php would have to read the value of the variable, do some logic, and echo a response.
You could use an <iframe> as an in-document 'pop-up', you just set the target of the form to the name/id of the iframe. (You can use some JavaScript to only show the iframe once the form is submitted.)
hi i need to validate the next page before printing it ...
what i did is i used i frame in the first page and called the page i needed to print
but it fired the query in the first page which should have been fire in the second page after the submission or click of the button ...
so i need to fire the php function after the button click which calls a function in javascript how should i do this?
could anybody help me...
Okay, I am not familiar with your level of PHP knowledge, so I will start with some basics:
PHP is a server-side scripting language. It compiles in real-time when a page is requested. The server processes the HTML and PHP and serves an HTML only page to the browser. You cannot execute PHP code on the client side. There is no way to get PHP code running at the time of a button press without the use of AJAX. You could use AJAZ to make a request to the server at the press of the button and fill the iFrame with the output.
Hope that helps.
so i need to fire the php function after the button click which calls a
function in javascript how should i do
this?
I am not quite clear on why you would need to do this but here it goes...
In the button click handler you want to make an AJAX call. I use jQuery but you can use whatever framework or XMLHttpRequest function you wish.
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
function ButtonClickHanlder( e ) {
// Prevent the button from doing something it's normal functions(ie submit form if it is a submit)
e.preventDefault();
// Make AJAX Call
$.post("test.php", { call: "callMe" },
function(data){
alert("Data Loaded: " + data);
}
);
}
$(function(){
$('#clicker').click(ButtonClickHanlder);
});
</script>
</head>
<body>
<a id="clicker" href="#">test</a>
</body>
</html>
Reference: http://docs.jquery.com/Ajax
The test.php page
<?php
if(isset($_POST['call']) && $_POST['call'] == 'callMe') {
callMe();
}
function callMe() {
echo "I am a php function. You rang?";
}
?>