UPDATE:
I need to get the jason.. The click event doesnt work why..
update:
<script>
$(document).ready(function(){
$("#RefreshButton").click(function(){
$.ajax({
url: "/test2/ajax.php",
type: "GET",
dataType: "json",
success: function(data)
{
alert("This is my data: "+data);
$(".article").remove();
$.each(data, function(key, value){
$('articleColumn').append( '<p class="article"><font size="5"><b>'+value[0]+'</b></font><br/>'
+value[1]+' Read more...</p>');
});
},
error: function( error )
{
alert(JSON.stringify(error));
}
});
});
});
</script>
The ajax call works..but not when it is in the click event handler..why?!?
I think the solution to the problem lies in the html:
<a href="" id="RefreshButton" >Refresh</a>
may be it refreshes the page and then send the response. I think it is the problem in the way the event propogates ..hmm
Generally when making an ajax call using jQuery I use the short hand version of POST and GET methods. So in your case I would do something like this
$.get("ajax.php", function(data){
alert(data); //just to make sure it works
}, "json");
Be sure to send the response back from ajax.php as json using json_encode(array("key"=>"value","key"=>"value")); ?>)
Also since ajax cannot go across domains you don't have to specify http://localhost/ajax.php, rather you can just specify it as the relative path to where you are calling the jquery function from.
Related
I'm newbie to jquery and AJAX and I have a really annoying problem with returning AJAX response simply into a div.
Code
$(document).ready(function() {
$.ajax({
method: "GET",
url: "lists2.php",
cache: false,
dataType: "html",
beforeSend: function() {
$("#sidebar-content").text("Loading..");
},
complete: function() {
$("#sidebar-content").text("");
},
success: function(lists) {
$("#sidebar-content").text(lists);
},
error: function() {
alert("Something went wrong..");
}
});
});
Code fires fine and no error appears, Firebug shows also no errors and if I put for example alert(lists) instead of .text() or .html() it works and alerts the data. But .text() or .html() don't work.
lists2.php is a complex file that analyzes data from SQL db and outputs the content inside a bootstrap sidebar. It worked fine in the old version without AJAX.
What am I doing wrong?
Complete() fires after success(), and is clearing your content.
Complete
A function to be called when the request finishes (after success and error
callbacks are executed). The function gets passed two arguments: The
jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object and a string
categorizing the status of the request ("success", "notmodified",
"nocontent", "error", "timeout", "abort", or "parsererror"). As of
jQuery 1.5, the complete setting can accept an array of functions.
Each function will be called in turn. This is an Ajax Event.
http://api.jquery.com/jquery.ajax/
I've created a custom wordpress plugin that should do the following:
on page load, submits a form
ajax catches it and does some other functions
results are returned
Only problem is that the plugin started redirecting to another page and looping infinitely. I've isolated it to the jquery submit code but I can't figure out what I'm doing wrong. I was hoping you folks could lend a sleep-deprived programmer a hand.
$('#searchform').submit(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '../wp-content/plugins/otwcsl/getStores.php',
data: $('#searchform').serialize(),
success: function(response) {
searchLocations(response);
$('#searchform').unbind().submit();
}
});
});
It worked fine on my localhost environment but went berserk on the 'live' website. I can't figure out the disconnect but I'm pretty sure the problem lies here. Thanks in advance!
UPDATE: I've cut everything down until it looks like this:
$('#searchform').submit(function(e) {
return false;
}
It's stopped looping but it redirects from http://www.mypage.com/index.php/locations/ to http://www.mypage.com/index.php/?s=. I can't figure it out since it's clearly not ajax that's affecting it.
FINAL UPDATE: I've finally fixed the problem. I removed all 'submit' functions and used a button click instead. I used the answer found here in option 3. I'm guessing there was some previous script that was severely messing with the form. Unfortunately, it's not an option for me to go disabling the scripts to find the root cause at this point. Thanks everyone for helping me troubleshoot it!
You have this code in the ajax call:
$('#searchform').unbind().submit();
In it you submit the form again. I guess that is what's going wrong.
infinite loop because you submit the form again if submit is seccussfull:
success: function(response) {
searchLocations(response);
$('#searchform').unbind().submit();
}
why submit again on success? remove it and it will work!
it should be:
success: function(response) {
searchLocations(response);
}
UPDATE:
your submit function should be like this:
var _form = $('#searchform');
_form.unbind();
_form.submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "../wp-content/plugins/otwcsl/getStores.php",
data: _form.serialize(),
success: function(response) {
//searchLocations(response); // check this method may be its submit the form again
}
});
});
Check the response from the server and set the propper datatype in the ajax call.
you can debug your ajax by using:
$.ajax({
url: $form.attr("action"),
type: $form.attr("method"),
data: $form.serializeArray()
}).fail(function(jqXHR, textStatus, errorThrown) {
console.log(jqXHR, textStatus, errorThrown);
}).done(function(data, textStatus, jqXHR) {
console.log(data, textStatus, jqXHR);
});
I have a web application which features a bunch of different items, which are generated from a MySQL table. As users scroll through it, I want them to be able to click a link next to the item which will insert the request into a MySQL database. Normally, I’d do this by creating a PHP page (which I will do anyways) that grabs the item name & user id from the URI using the $_GET method & inserts it into the table. However, in this case, I don’t want the users to be redirected away from wherever they are. I just want the link to send off the request, and maybe display a small message after it is successful.
I figured jQuery/AJAX would be best for this, but as I’m not too familiar with it, I’m not sure what to do. Any tips are appreciated!
You have to do something like
$('.classofyourlink').click(function(e){
e.preventDefault();//in this way you have no redirect
$.post(...);//Make the ajax call
});
in this way the user makes an ajax call by clicking a link without redirecting. Here are the docs for $.post
EDIT - to pass the value to jQuery in your case you should do something like
$('.order_this').click(function(e){
e.preventDefault();//in this way you have no redirect
var valueToPass = $(this).text();
var url = "url/to/post/";
$.post(url, { data: valueToPass }, function(data){...} );//Make the ajax call
});
HTML
<a id="aDelete" href="mypage.php">Delete</a>
Script
$(function(){
$("#aDelete").click(function(){
$.post("ajaxserverpage.php?data1=your_data_to_pass&data2=second_value",function(data){
//do something with the response which is available in the "data" variable
});
});
return false;
});
See http://api.jquery.com/jQuery.ajax/
$('#my-link').click(function(){
$.ajax({
url: "mypage.php",
context: document.body,
success: function(){
$(this).addClass("done");
}
});
return false;
});
$('.classOfYourLinkToBecliked').click(function(){
$.ajax({
type:'GET',
'url':'yoururl',
data: {yourdata},
processData: false,
contentType: false,
cache: false,
dataType: 'json',
success: function(response){
alert(response);
}
});
});
I'm trying ajax for the first time but it doesn't work.
This is "some.php" which handles the ajax call:
<?php
echo "success";
?>
And this is the javascript that calls it:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.min.js"></script>
<script type="text/javascript">
var msg;
$.ajax({
type: "POST",
url: "some.php",
data: ({ })
success: function(msg){
alert( msg );
}
});
</script>
Can you see where the problem is?
I should state I'm working under wordpress and both files reside in \wp-content\themes\twentyten (maybe the url in the ajax call is wrong?)
First of all remove the data:({}) which is pointless. you are also missing a , behind your data statement. this is most likely the issue.
if both the files is in the same directory, then the url should be correct.
However, i urge you to use a tool like FireBug in order to debug your problem further
You should run your script when the page has loaded (more precisely, when the DOM is ready). jQuery offers an event for that.
Your code could then look something like this:
$(document).ready(function(){
$.ajax({
type: "POST",
url: "some.php",
data: ({ })
success: function(msg){
alert( msg );
}
}
});
Two things to do:
register a .fail callback. The code as it is will just call the alert() if it succeeds, otherwise, errors are not raised. See http://api.jquery.com/jQuery.ajax.
check the web server log to see if some.php is exec'd and if so, what errors may be occurring on the server.
I have some ajax/jquery code in one of my pages and the problem I'm having is that it doesn't work the first time the page is loaded. If I refresh the page it works no prob. It does work in firefox first time. All the variables that I'm using are ok as I've alerted them out. I don't get a success or error message. It justr doesn't appear to do anything?
Any ideas?
$('.window .request').click(function (e) {
var itm = document.getElementById('txtItm').value;
var qty = document.getElementById('txtQty').value;
var msg = document.getElementById('txtMessage').value;
var op_id = document.getElementById('txtOp_id').value;
$.ajax({
type: "POST",
url: "do_request.php?msg="+msg+"&itm="+itm+"&qty="+qty+"&op_id="+op_id,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
document.getElementById('div_main').style.display='none';
document.getElementById('div_success').style.display='block';
var row_id = document.getElementById('txtRow').value;
document.getElementById('row'+row_id).style.backgroundColor='#b4e8aa';
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('Error submitting request.');
}
});
});
It's hard to determine what the problem might be given the information and it sounds like you've not fully tested the page in a consistent manner. It seems likely there is another element on the page affecting the click event, as opposed to the handler logic itself, but there's no way to tell. Make sure you are binding to the click event after the page is ready:
$(document).ready(function(){
$("#uniquedomid").bind('click',function(){
// click handler logic
});
});
Also, as you're new to JQuery, one thing you're going to want to start looking at are all the various ways in which JQuery can improve your life. It does almost everything. But for starters, you're going to want to start using:
$("#uniquedomid")
Instead of
document.getElementById("uniquedomid")
And
$("#uniquedomid").val();
Instead of
document.getElementById("uniquedomid").value