This is the code . Ajax is only running once when i run in the IE. But with all other browsers it is running great.
Untitled Document
function cool_add()
{ //alert(post_id);
var txt1 = $("#txt1").val();
$.post('jqueryphp.php', {txt1:txt1}, function(data) {
var dat = data;
$("div").html(data);
});
}
</script>
</head>
<body>
<form>
<input type="text" id="txt1" /><br />
<input type="button" id="butn" onclick="cool_add();">
</form>
<div></div>
</body>
</html>
It is running great in all other browsers but with IE it only runs once thats it.
IE tends to cache all request and if the request params are same then it will return the cached response. To avoid this, you can use $.ajaxSetup following code which will be applied globally for any future ajax calls.
$.ajaxSetup ({
// Disable caching of AJAX responses
cache: false,
});
You can also apply this cache on a specific call as below,
$.ajax ( {
//..other params
cache: false,
//..other params
});
When cache=false, jQuery will add current timestamp to each request so that the request params are unique.
In your ajax call, make sure to include
cache: false
IE caches everything, so it assumes your calls are all the same.
I suspect this is the caching issue I identified in your question yesterday.
http://www.gtothesquare.com/2010/09/26/if-jquery-ajax-call-not-working-in-internet-explorer-try-this/
Related
I have a
$(".clickButton").click(function() that loads a page using $.ajax and return the result to a DIV. This works perfectly in Chrome, FireFox and Safari, but not IE11.
$.ajax({
url: "go.php?ab=1",
success: function(data, textStatus, xhr) {
$("#res").html(data);
}
});
As a quick test I tried the following and again it works in Chrome, FireFox and Safari but not IE11.
$.get('go.php?ab=1', function( jqXHR, textStatus, errorThrown )
{ alert(jqXHR); });
The date being returned is text and is either OK or ERROR.
The go.php is running multiple command line scripts and depending what the variables passed depneds on what runs.
All that part is fine and it works really well in the 3 browsers, but not IE11.
When the page first loads in IE it sort of works, it appears to run the go script and return a result. But any subsequent click return instant and the go.php page isn't called. Results are displayed but they appear to be the first processes return results. It's as if the result and process have been cached.
Any ideas how to make this work in IE as it does in the others ?
It's as if the result and process have been cached.
This is possible. If you are sending multiple GET requests to the same URL your browser may be caching the result. If you wanted to verify this you could click the button, clear your cache without reloading the page, and click the button again to see if it works as expected this time.
To prevent caching of GET requests you can add
cache: false
to your $.ajax options for each request, or you could disable it for all requests by using
$.ajaxSetup({ cache: false });
I dont know if we been to the same problem, but just earlier I was trying to get the responce data from the go.php and add it into a div.
My code goes like this.
onClick:
<script type="text/javascript">
function gimmeData(){
var url = 'go.php';
$.ajax({
type: "GET",
url: url,
data:{'something':'1'},
success:function(results)
{
$('#add_data').html(results);
}
});
}
</script>
this will give go.php?something=1 url.
html:
<input type="button" onclick="gimmeData();" value="clickme!" />
<div id="add_data"></div>
button click
$('a').on('click', function(){
var a = $(this).data('first');
var b = $(this).data('second');
alert(a + ":" + b);
});
html:
<a id="button" href="#" data-first="something" data-second="something2" onclick="click();">click me</a>
using data() function. see http://api.jquery.com/data/
or you can do $(this).attr("data-value") to get the value of a data-attribute
JSFiddle sample.
i am trying to create a form submit when checkbox is changed
my code is given below. . my problem is nothing happens on
gotofile.php
file but //dosomething
on the sucess function is executed
the jquery:
$("#container input[type=checkbox]").change(function(e){
if($(this).attr('checked'))
{
var cnType=$(this).attr("id");
$.ajax({
type: "POST",
url: "gotofile.php",
data: "typID="+cnType ,
cache: false,
success: function(){
//do something
}
});
}
});
the php:
include '../dbconnection/dbconfig.php';
$typeID=$_POST['typID'];
$qryConnections="INSERT INTO ...";
$rslt1 = mysql_query($qryConnections);
the html
<form id="cnct" method="POST">
<div id="container" style="">
<ul style="list-style: none;">
<li><input type="checkbox" id="1" />A</li>
<li><input type="checkbox" id="2" />B</li>
</ul>
</div></form>
Can any one help me what i am doing wrong?
A couple of security issues
Always keep in mind that your JS is viewable to anyone that navigates to your site. Using:
data : "typID="+cnType
Would make me think that typID is the field in your SQL. You have no CSRF filter, therefore I could write an ajax script to spoof valid requests and update all of your fields from an external location. Something to keep in mind, I recommend you read up on CSRF or Cross Site Request Forgery.
Why doesnt your script work
If the success function is firing, then the script has run. Debug it by outputing the value of $_POST['typID'] in your PHP. You will see the variables value in the console if it sent correctly.
As well as this it's always good to have your PHP echo out a JSON response for your success function to validate that all went well.
echo json_encode(array('response' => 'success'));
or ('response' => 'failed') or whatever you need. You can then evaluate the JSON in your success function.
I hope this helps.
The first thing is you should use click instead of change event for the checkbox in your Jquery code.
The second thing, you did not provide any value to the checkbox in your html code.
Kindly ask if it not worked for you.
Try
$("#container input[type='checkbox']").click(function(e){
var cnType=$(this).attr("id");
$.ajax({
type: "POST",
url: "gotofile.php",
data: "typID="+cnType ,
cache: false,
success: function(){
//do something
}
});
});
I'm about to pull the hair out of my head with this one.
I'm sure the problem is simple, I'm new to Ajax with Jquery and I'm just overlooking something. But Man this is annoying. Every time the form is submitted, the page refreshes and .ajax throws error:. What could be causing this? I know I'm getting my form values to the Jquery for sure. And newcomment.php is working. I can post regular forms to it, but not with jquery.
function postPhotoComment() {
var comment = $("#comment").val();
var album = $("#album").val();
var photo = $("#photo").val();
var dataString = "comment="+comment+"&album="+album+"&photo="+photo;
$.ajax({
type: "POST",
url: "/includes/actions/photo-gallery/newcomment.php",
data: dataString,
success: function(res) {
alert("Posted!");
}
error: function(res) {
alert("Error!");
}
})
}
EDIT: Here's my html form:
<form>
<textarea id="comment" placeholder="Post Comment..."></textarea>
<input id="album" type="hidden" value="<?php echo "$a"?>"/>
<input id="photo" type="hidden" value="<?php echo "$p.$ext"?>"/><br/>
<button id="photo-comment-submit" onclick="postPhotoComment()">Post</button>
</form>
I also noticed that if I give the inputs names, Chrome puts them into the url bar like GET variables. And after every page refresh, it adds the ? at the end of the url. So, it seems like its trying to submit the form regularly.
Are you returning false to stop the browsers default action?
$('form').submit(function(){
var dataString = $(this).serialize(); // shortcut
$.ajax({
type: "POST",
url: "/includes/actions/photo-gallery/newcomment.php",
data: dataString,
success: function(res) {
alert("Posted!");
}
error: function(res) {
alert("Error!");
}
});
return false;// cancels the default action
});
If the function where you're calling the AJAX form submission code is the onSubmit method of the form, you'll need to stop the default action from happening -- that is, you want to stop normal submission.
To accomplish this, use the preventDefault method of the event object:
function postPhotoComment(evnt) {
evnt.preventDefault();
// existing code continues...
}
You may also return false from your event, but be aware that doing so has different effects in different browsers, and that it is not as explicit or reliable as calling preventDefault or stopPropagation directly.
Edit
Also, the error handler is probably getting called because your code initiates the XHR request, but when the browser starts the default action (submitting the form), it cancels any pending XHR requests. This is causing the error handler to be triggered.
Edit 2 I have created a jsFiddle with a working demonstration: http://jsfiddle.net/wXrAU/
Documentation
event.preventDefault method on MDN - https://developer.mozilla.org/en/DOM/event.preventDefault
Make sure that you return false; to the form when submitting, otherwise it will still submit as a "normal" form without using Ajax and reload the page.
EDIT: After reading the comments I think that this would be most appropriate for you:
<form action="url.php" onsubmit="return false;"></form>
jsFiddle with appropriate code: http://jsfiddle.net/SO_AMK/ZVgNv/
The PHP messes things up a little, but it works.
I actually fixed this by simply removing the <form> tags. I didn't need them anyways. But everything seems to work now.
Make sure you write a valid, HTTP-accessible url instead of just a path to a script, e.g.
function postPhotoComment() {
var comment = $("#comment").val();
var album = $("#album").val();
var photo = $("#photo").val();
var dataString = "comment="+comment+"&album="+album+"&photo="+photo;
$.ajax({
type: "POST",
url: "http://yoursite.com/whatever/newcomment.php", // here
data: dataString,
success: function(res) {
alert("Posted!");
}
error: function(res) {
alert("Error!");
}
})
}
Because JavaScript is a client-side language. It knows nothing about your filesystem structure or anything of that kind. And AJAX request is based on HTTP protocol.
This is my form:
<form id="submitsearch" action="Classes/system/main/searchresult.php" method="POST">
Search by <span style="font-size:15px;">(developer, specialization, profession,major)</span>
<input type="text" name="searchbox" id="searchbox" />
in
<select style="text-align:center;" name="countrysearch" id="countrylist">
<option selected="selected" value="0">None</option>
<option value="1">USA</option>
</select>
<input style="margin-left:25px;" id="submitSearch" type="submit" value="Search"/>
</form>
and this is the Ajax jquery code:
$("#submitSearch").click(function(){
$.ajax({type:'POST', url: 'Classes/requests/search.php', data:$('#submitsearch').serialize(), cache: false, success: function(response) {
$('#submitsearch').find('#pagePanel').html(response);
});
Why isn't it working ? The php file is returning the correct result normaly.
But i want it to load inside another div with an id "pagePanel" without reloading, using ajax.
Any help ? I'm new to Ajax.
Edit:
$("#submitbutton").click(function(){
$.ajax({type:'POST', url: 'Classes/system/main/searchresult.php', data:$('#submitsearch').serialize(), cache: false, success: function(response) {
$('#pagePanel').html(response);
}})});
This worked out with me.
Thanks for all your help.
If you have a input of type submit, it will, guess what :), submit the form, and therefore reload the page. Turn it into:
<input style="margin-left:25px;" id="submitSearch" type="button" value="Search"/>
Then make sure you actually have a pagePanel element in your html.
And now a couple of suggestions:
don't id your form #submitsearch and the button as #submitSearch... confusion may arise
you can use AJAX's .load() instead of .ajax() to get directly the result in the DIV:
So:
$("#pagePanel").load('Classes/requests/search.php', {$('#submitsearch').serialize()});
If you want to use ajax in the form submition you'll need to cancel it.
$("#submitSearch").click(function(event){
$.ajax({type:'POST', url: 'Classes/requests/search.php', data:$('#submitsearch').serialize(), cache: false, success: function(response) {
$('#pagePanel').html(response);
});
event.preventDefault();//prevents submitting of the form
}
First you need to stop the default form submittal. return false in the submit handler to stop default. Just use the ID of the element without using find() to insert data into. The elemnt you are trying to find doesn't appear in your html though within the form where your code suggests it should be
$("#submitSearch").click(function(){
$.ajax({type:'POST',
url: 'Classes/requests/search.php',
data:$('#submitsearch').serialize(),
cache: false,
success: function(response) {
$('#pagePanel').html(response);
}
})
return false;
});
After pushing the submit button, the default behaviour is to submit the form and indeed go to the action URL you provided to your form. Now, you want to prevent that behaviour. This means, you'll have to look at the onsubmit event of the form, and prevent the actual submission. jQuery has a preventDefault() method to do this.
In your case, all you'll have to do is add the following code:
$(document).ready(function() {
$("#submitsearch").on("submit", function (e) {
e.preventDefault();
});
});
And here is a jsFiddle to demonstrate it.
You can obviously do the same thing to your submit button, just add the e variable as the argument to your click event and use e.preventDefault() to cancel the actual submit (but you can still perfectly do the AJAX request).
First of all, you are missing a few closing parenthesis and curly brackets. Be sure to run your dev tools in your browser to check console for errors like that. I normally don't use $.ajax...I usually use $.post, but using what you have so far, I would rewrite to something closer to:
$("#submitsearch").submit(function(){
var submitData = $(this).serialize();
$.ajax(
{
type:'POST',
url: 'Classes/requests/search.php',
data: submitData,
cache: false,
success: function(response) {
$('#pagePanel').html(response);
}
}
);
return false;
});
Instead of sending back loads of HTML to the page, you could just send results in form of a set of JSON objects and then dynamically create the HTML based on the results, this means a lot less data being sent back to the browser which is quicker and more efficient.
I've run into a strange issue with Webkit based browsers (both Safari and Chrome - I'm testing on a Mac) and I am not sure what is causing it. Here's a small script I've created that replicates the issue:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
function doRequest() {
document.test.submit();
$.ajax({
type: "GET",
cache: false,
url: 'ajax.php?tmp=1',
success: doSuccess
});
}
function doSuccess(t_data,t_status,req) {
alert('Data is: '+ t_data +', XMLHTTPRequest status is: '+ req.status);
}
</script>
</head>
<body>
<form name="test" method="post" action="ajax.html" enctype="multipart/form-data">
<input type="file" name="file_1">
<br><input type="button" value="upload" onclick="doRequest();">
</form>
</body>
</html>
ajax.php is:
<?php
echo $_REQUEST['tmp'];
?>
This works as is on Firefox, but the XMLHTTPRequest status is always "0" on both Safari and Chrome. If I remove this line:
document.test.submit();
then it works, but of course the form is not submitted. I've tried changing the form submit button from "button" to "submit", but that also prevents it from working on Safari or Chrome.
What I am trying to accomplish is:
submit the form
call another script to get status on the file being uploaded via the form (it's for a small upload progress meter).
Any help is really appreciated - I'm hopeful it is just a quirk I'm not familiar with.
Thanks!
Brian
Simply put: you cannot upload files using AJAX.
There are nice plugins such as jquery form that will handle this automatically (by creating a hidden iframe and performing the real file upload).
I think FireFox has a native file upload API but if you want a cross browser solution you will need to take a look at some plugins. Using a flash upload is another solution.
My experience while developing a similar upload checking tool1 is that you should use both success: .. and complete: ... They would probably do the exact same thing in your code and you can have them call the same function. complete: gets called when the request finishes, success: when a request succeeds. Thus maybe:
function doRequest() {
document.test.submit();
$.ajax({
type: "GET",
cache: false,
url: 'ajax.php?tmp=1',
complete: doSuccess,
success: doSuccess
});
}