I currently have links w/ class="ajax" that I want to retrieve the element with id="test" from the file "data.html" in the same directory, and put that content into the id="content" div on my page:
<script>
$(document).ready(function(){
$("a.ajax").click(function(event){
$("#content").load("/data #test");
});
});
</script>
<a class="ajax" href="#">Text</a>
<div id="content"></div>
and externally, but in the same directory, I have data.html:
<div id="test">Will this show up?</div>
On the clicking of the anchor, Safari reports "page loading interupted", and no change occurs.
I definitely have JQuery called in the header. Can I get some help with this function? Thanks!
You have /data but the file is /data.html, assuming you're in the root. :)
I just tested what you have with this change and it works fine for me. I also recommend you get a tool like Firebug so you can easily see what your AJAX requests are doing.
$.ajax({
url: "data.html",
type: "POST",
success: function (answer) {
$("main_content").html($(answer).find("div#content_id").html());
}
});
I hope it will help you.
Related
I have PHP code which successfully gets the contents of a directory on my server.
I wish to then write this array to a specific div on my main html page (so that I can parse this later and use this information further)
Currently my PHP navigates me away from my current page to write this array which I want to prevent.
Furthermore I wish to do all of the PHP work on a button click, and return the values on the main html page after.
How can I do this???
My button on my html page is as follows:
<form action="PHP_Function.php">
<input type="submit" class="learnButton" name="insert" value="Find Available Evidence" />
</form>
And my PHP code looks like this to carry out the work:
if (isset($_POST['action'])) {
switch ($_POST['action']) {
case 'insert':
insert();
break;
}}
I have an array: "IfPresentArray" which I then wish to write to my main html page:
if(in_array("Facebook.xml", $dirArray)){
$IfPresentArray[0]="1";
}else {
$IfPresentArray[0]="0";
}
Any help would be greatly appreciated as I am very new to PHP.
Thanks in advance
You need to use AJAX techniques to do this. Use a Javascript framework like jQuery to react to the button click, make a request to your PHP script, and then update the contents of the div.
See http://api.jquery.com/click/ for handling clicks, and http://api.jquery.com/jQuery.ajax/ for making the request.
Good luck!
You will need to use an ajax call. This allows your to click some div, send something to the server, receive a response and display an output in many different formats.
You can either reference the jQuery library in your header
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
or just download it and save it whereever
Here is a basic ajax call:
<script>
$(document).ready(function(){
$('#someval').click(function(){
var content = $('#somecontenttoadd').val; //this could be many things... etc(.text, .html)
$.ajax({
type:'post',
url: 'PHP_Function.php',
data: 'action='+content,
success: function(resp){
$('#somediv').html(resp); //lets put the information into a div
//this could be anything response format like .val or .text instead of .html
},
error: function(e){
alert('Error: ' + e);
}
});
});
});
</script>
HTML -- you can get rid of the tags and just use the id of the object.
<input type="submit" class="learnButton" name="insert" value="Find Available Evidence" id="someval"/>
As others said, AJAX is the solution, I will give you the code that works for me, so that you have an exact starting point.
As I understand you have a separate html page and a php file that includes your function.
In order to make this work you will have to implement a function with an AJAX call.
This should be placed in a javascript file and will be invoked after the form submit button is clicked on the html page.
The AJAX call will then invoke your php function, get the response data back from php.
The javascript function will update the html page in the end.
You will need three files:
main.html
script.js
function.php
Let me replace my original answer with a full example of the three files.
main.html
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="/script.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<form id="myForm" method="post" action="function.php">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Name">
</div>
</form>
<div class="modal-footer">
<button type="submit" form="myForm" class="btn btn-primary" id="SaveButton">Submit</button>
</div>
<div id="resultbox">
</div>
</div>
</body>
</html>
Here we included jQuery, our own javascript and bootstrap just to look better. the form action is our function.php, the form 'id' is used in our jQuery code. the "result box" box will display the response.
script.js
$(function(){
$("#myForm").submit(function(event) {
$.ajax({
type: "POST",
url: $(this).attr('action'),
data: $(this).serialize(),
dataType: 'json',
success: function(data)
{
//display data...
$("#resultbox").html(data.name).show;
}
});
return false;
});
});
this will override the default form submit behavior. I had a typo here in the original answer, I fixed it. url and data are taken from the html form, dataType is set to json, because we expect a json back.
function.php
<?php
echo json_encode(array('name' => $_POST['name']));
Our php code is just one line, we build an array and return it as json. You can then used in jQuery, just like any other json, as shown in the above code.
I have a main view that let's say has the following:
<div id='test'>Some Text</div>
<div id='placeholder'></div>
then using ajax I'm replacing the contents of 'placeholder' with a partial view that looks like this:
<div id='ajaxContent'>
// new content
</div>
<script>
$(document).ready(function() {
console.log($('#test').text());
$('#test').css('color','red');
});
</script>
so in my script I'm trying to change the color of the text in div 'test' to red, but I keep getting 'undefined' in the console. How do I access the test div in the main view from the partial view coming into the main view through ajax?
If they're ending up on the same page, shouldn't the html elements be able to see each other?
Your JavaScript fragment is simply removed by jQuery on html(...) call. A similar issue can be found here: jQuery .load() / .ajax() not executing javascript in returned HTML after appended
Thus, you have to insert partial data in this manner (assuming you have your partial respone in result variable):
$(result).find('#ajaxContent').appendTo('#placeholder');
$(result).find('script').appendTo('#placeholder');
Also, as #RolandBertolom said before, you don't need ready() in your partial response in JavaScript.
You actually do not need to use $(document).ready. It's just useless. But it shouldn't break anything. As well as you can access any element on the page from script inserted anywhere in the same document. So problem is somewhere out your question's scope.
Try:
run $('#test').text() from console.
replace $('#test').text() with $('body') or something else in your script.
...
Be deductive when you debugging! ;-)
you should not be using $(document).ready again because you document will already loaded with main page so again using it wont help.
try like this:
suppose this is your test.php:
<script>
jQuery(document).ready(function() {
$.ajax({
type:'post',
url:'submit.php',
success:function(data) {
$('#placeholder').append(data);
}
});
});
</script>
<div id='test'>Some Text</div>
<div id='placeholder'></div>
//this is your submit.php the content to replace
<?php
echo "<div id='ajaxContent'>
</div>
<script>
$(function(){
console.log($('#test').text());
$('#test').css('color','red');
});
</script>";
?>
NOTE: what i exactly mean here is use:
$(function(){
console.log($('#test').text());
$('#test').css('color','red');
});
in script.
I want to send a login form to a site without having the page redirect to that site but rather just display a blank page instead. I have been looking around and noticed jquery would help me with this but I haven't found a way to get it to work quite right so I was hoping for some advice. This is what I have right now.
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<form id="myForm" action="placeholderurl" method="post">
<input type="hidden" name="username" value = "placeholder"/>
<input type ="hidden" name="password" value = "placeholder"/>
<input type="submit"/>
</form>
<script>
$(document).ready(function() {
$('#myForm').submit(function(e) {
e.preventDefault();
var formdata = $('#myForm').serialize();
$.ajax({
url: "placeholderurl",
type: "POST",
data: formdata,
cache: false,
success: function(data) {
alert("yeah");
//?code to display blank page after successful login??
},
error: function(){
alert("noo");
}
});
});
});
</script>
</head>
</html>
Currently, the code always goes into the "noo" error block. I'm not sure how to extract more information out of the error so I don't know exactly what is going wrong. Any advice/tips would be appreciated.
*Edit
The placeholderurl and placeholder are filled in with the correct information in my actual code. Also, the url I want to post to is not in the same domain as the function is being called from so ajax may not work for this(comment from Archer). Since this is the case, is there another way to get the desired behavior that I can try without using ajax. Thanks again.
I'd suggest watching your network traffic in something like Fiddler, Firebug, or Chrome's developer tools and see what the response is that is causing the error. I'm guessing your placeholderurl is on a different domain and your call is failing due to that.
I am trying to rewrite this link so instead of linking to a light box, it makes an ajax call and updates the contents of <div class = "add-rule>. Here is the link
<div class="add-rule>"Add a rule</div>
I am new to Javascript and Ajax, so any help would be much appreciated.
The code should look some like this (couldn't check this out but I am not far away)
For more info have a look at jquery's ajax api
and you might be interested in the load function.
This is my code, let me know if it fits or not
<div class="add-rule">
<span id="addRuleError"></span>
<a href="javascript:void(0)" onclick="loadContent()" class="lightwindow"
params="lightwindow_type=external,lightwindow_height=100,lightwindow_width=300">Add a rule</a>
</div>
<script type="text/javascript">
function loadContent()
{
$("#addRuleError").text("");
$.ajax({
url:"saffron_main/add_rule",
data:{type:"tid", mid:0, cid:1, "m-name": "valid"},
success:function(result){$(this).parent().html(result)},
error:function(result){$("#addRuleError").html(result.responseText)}
})
}
</script>
When I use Ajax call(jquery) in the HEAD section I find a "waiting for response message" on a chrome browser with revolving circle. I don't want this ugly look. Is there a way to avoiding this?
PS: When I use input tag to call the JavaScript(Ajax call) function like
<input id="launcher" type="button" onfocus="go()" value="Go!"></input>
I couldn't see a waiting circle. Cause my program should call the function automatically I couldn't use this method.(If I use document.getElementById("launcher").focus() to automatically start the function, It showed waiting circle again.) I guess there's a some different context to call JavaScript function.
Update Here is my sample code
<HEAD>
<SCRIPT TYPE="text/javascript">
function go() {
$.ajax({
url: "/myService",
success: function(data){
document.getElementById("result_area").innerHTML = data;
go();
}
});
}
$(document).ready(function(){
go() //Here I want to Comet call;
});
go(); //should start automatically.
</SCRIPT>
</HEAD>
<BODY>
<!-- <input id="launcher" type="button" onfocus="go()" value="Go!"></input>
This doesn't show the waiting circle. Why? Use different call context? -->
<div id="result_area"></div>
</BODY>
there are some issue i want to highlight
<input id="launcher" type="button" onfocus="go()" value="Go!"></input>
this should be
<input type="button" id="launcher" value="Go!" />
then
if u want a image instead of text then put a div before form with display:none
in ajax call you are not writing url link with extension (.php or .html or .js )
in success : you again calling go(), this smell like recursive function
what data u r sending to the server?? data: is missing from ajax option
also mention dataType ( optional)
if you dont want to run ajax automatically then do it on some event( like i do on click)
bind with the document ready
write javascript code in head ( best practice to write just before </body> )
i tried my hard to tell you the basic, here is my way
HTML
<div id="waiting" style="display: none;">
<img src="images/ajax-loader.gif" title="Loader" alt="Loader" />
</div>
<form>
// here is your form
</form>
jQuery
<SCRIPT TYPE="text/javascript">
$(document).ready(function(){
$('#waiting').show(500);
// instead run automatically now it will work on click of button
$('#launcher').click( function () {
$.ajax({
url: "/myService.html", // or whatever page
// by the way where is data which you sent on server??
data: { email : $('#email').val() }, // like i send the email to the serever
dataType : "json",
async : false,
success: function(data){
$('#waiting').hide();
$("#result_area").html(data);
}
});
});
})
I found that this waiting circle on XMLHttpRequest is depend on a browser implementation. On IE7, Firefox4 it didn't show any waiting circle or bar while chrome11, Windows safari had one.
I believe that standard on this should be made cause it impacts greatly on user experience.