AJAX on click not calling/loading as it should - ajax

I have been learning AJAX for the best part of 2 hours, trying to get my head around how to get this to work, it seems it is calling the function as if I put an alert in, it all works fine.
I tried using another method and it seemed to call the function on it's own and it would load what the .php page is echoing.
What am I doing wrong in order for it to not work at all?
<script type="text/javascript">
$('a.fire').click(call_ajax);
function call_ajax() {
$.ajax({
type: "GET",
url: "http://127.0.0.1/onlineshop/admin/scripts/test.php",
dataType: "html",
success: function(html){
$("#holder").append(html);
}
});
}
</script>
Edit: I have also just tried
$('a.fire').click(function() {
$.ajax({
type: "GET",
url: "http://127.0.0.1/onlineshop/admin/scripts/test.php",
dataType: "html",
success: function(html){
$("#holder").append(html);
}
});
});
Which also does not work.
EDIT: I have now got code that GET's the php file I wanted, but for some reason does it on it's own
<script type="text/javascript">
function call_ajax() {
$.ajax({
type: "GET",
url: "http://127.0.0.1/onlineshop/admin/scripts/test.php",
dataType: "html",
success: function(html){
$("#holder").append(html);
}
});
}
<script type="text/javascript">
$(function() {
$(document).ready(function() {
$('a.fire').click(call_ajax());
});
});
The issue with this code is that it fires on it's own
EDIT: Now have new code, that is attempting to fire according to Firebug console but I get the alert ERROR: error, so I don't have a clue what is happening in order for it to fail, I have also tried many different URL's with no working solution
$('a.fire').click(function () {
$.ajax({
type: "GET",
url: "/onlineshop/admin/scripts/test.php",
dataType: "html",
success: function(html){
$("#holder").append(html);
},
error:function(xhr, text, error){
alert("Error: " + text);
}
});
});
SOLVED: I have now got it to work! For some reason my anchor had a href of "", which would cause it to reload the page and removing my GET from the page

ajax will only work if it's the same domain. This means that if you execute jQuery from domain x to domain y, it won't work. This is for safety-reasons to prevent websites from loading from another website. Does your jQuery-ajax call work if you remove the 127.0.0.1 from your url?
Furthermore I guess you should add the click-function inside your $(document).ready(); function, like this:
$(document).ready(function(){
$('a.fire').click(function() {
$.ajax({
type: "GET",
url: "onlineshop/admin/scripts/test.php",
dataType: "html",
success: function(html){
$("#holder").append(html);
}
});
});
});
for testing purposes, you can also use the complete function inside your ajax and alert your data. firebug can be helpful too to find your problem :)

Related

How to use ajax with autocomplete in jquery

I have the following jquery with ajax call? My webservice returns dataset.
Here is the code:
$(document).ready(function(){
$('#ctl00_ContentMain_ddlRegions').change(function(){
region = $(this).val();
alert(region);
});
});
$('input[type="text"]').autocomplete({
$.ajax({
async: true,
type: "GET",
url: "~/EmailActivation/EmailActivation.asmx/GetIsoFromRegion",
data: "{'option':'" + region + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
success: function(data,status){
alert("success");
}
});
minLength: 4 });
});
Right now there is an error in my code so, I cannot even display alert to show region. Error is generated from autocomplete section.
When I remove autocomplete section, script works.
What do I need to change and how can I make my autocomplete work with the data coming from webservice?
Thank you

working XML feed , blogger is an exception?

This is a working fiddle. http://jsfiddle.net/bpBtC/1/
But this http://jsfiddle.net/bpBtC/131/ doesn't work with the same method?
(All the other websites with XML feeds also fail using the same method, why?)
$(document).ready(function () {
$.ajax({
type: "GET",
url: "http://www.blogger.com/feeds/2399953/posts/default",
dataType: "xml",
success: xmlParser,
dataType: 'jsonp'
});
});
function xmlParser(xml) {
$(xml).find("entry").each(function () {
$(".entirecont").append($(this).find('title').text());
});
}
You are setting dataType twice.
$(document).ready(function () {
$.ajax({
type: "GET",
url: "http://www.blogger.com/feeds/2399953/posts/default",
dataType: "xml",
success: xmlParser,
dataType: 'jsonp' //<-- this is what actually used.
});
Remove the second dataType and your code will fail.http://jsfiddle.net/bpBtC/130/
The first fiddle works because it is using JSONP (not XML) as the return data type and a method of circumventing the cross-site scripting restrictions. Familiarize yourself with JSONP and how it works.
The second feed does NOT return JSONP, it returns XML and so it can't work. Also you can't have two datatype-parameters on same ajax-call.

Linking AJAX with PHP code. Do i need to write it again?

I have a real problem. I have a php code and a form where when the form is submitted a POST request is sent and the page reloads again and ofcourse the post is viwed in the page.But i want to work with AJAX in order page not to be refreshed.I know the basics of AJAX but i don't want to build all the project from the beggining.Is there a way in success function of AJAX to link to my php code??
$.ajax({
type: "POST",
url: "index.php",
datatype: "html",
data: dataString,
success: function(data) {
//How can i link here to start running my php code which is located in the same page.
}
});
$.ajax({
type: "POST",
url: "somescript.php",
datatype: "html",
data: dataString,
success: function(data) {
// try this
console.log(data);
// see what 'data' actually is
}
});
then check in the browser by hitting F12 to look at the console.
also are you sure you want datatype of html ? you probably want a data type of json or XML , what is the server returning to you after the ajax post?
You have to cancel the form's submission so that the ajax request will take place, otherwise it is canceled. Also use .serialize to get a name-value pair string of the form data to use in the ajax call.
Html
<form id="MyForm">
<button id="MyButtonId">Submit</button>
</form>
JS
$("#MyForm").submit(function(e){
//Prevents the form from being submitted
e.preventDefault();
$.ajax({
type: "POST",
data: $("#MyForm").serialize(),
url: "somescript.php",
datatype: "html",
data: dataString,
success: function(data) {
alert(data);
}
});
});

JQuery Ajax call often not working on Safari 6

My Ajax call is really simple as below:
function ajax(reqUrl, params , callback) {
console.log("Request URL "+reqUrl);
var cond;
cond = $.ajax({
type: 'post',
url: reqUrl,
data: params,
error:function(){ alert("some error occurred") },
success: callback
});
console.log("Server response "+cond.readyState);
}
// Call it as
var url = "/getResult";
var params = {};
params.param1 = "test1";
params.param2 = "test2";
ajax(url, params, function(returnCallback) {
console.log(returnCallback);
alert("Success");
});
That works fine in most cases. But sometimes (about 1 times in 3) it doesn't return anything to callback.
I found many questions and answers for Not working ajax in Safari but fine in chrome and FireFox. My problem is different from them, because it's fine most of the time (I don't mean it was not fine usually because when I refresh my browser, that may cause my ajax call to work).
My main question is why does my ajax call sometimes fail? I don't get any errors on my JS console. When this situation, I refresh my browser to get my ajax call to. Any Ideas?
Update:
I found that sometimes my ajax call method didn't call out because console.log("Request URL "+reqUrl); did not execute. When I don't want to refresh my browser, I clicked many times on my page's link to produce result. will something late to execute?
Finally, I found error .. Safari doesn't reload my JavaScript files again even disable Cache. So I put all of my JS code into:
$(document).ready(function(){
// start load my js functions
init();
});
to reload my JS files when my page was ready. Cheer !
I also met this problem.
When I moved all code into $(function() {}), it worked.
After that, I found I had defined a variable named key, which caused the problem.
Just rename it, all things will be running.
This seems to be a Safari issue. In this post there is a suggestion to add a beforeSend to your ajax-request.
In your case:
cond = $.ajax({
type: 'post',
url: reqUrl,
data: params,
beforeSend: function (event, files, index, xhr, handler, callBack) {
$.ajax({
async: false,
url: 'closeconnection.php' // add path
});
},
error:function(){ alert("some error occurred") },
success: callback
});
Please Test below Code. it is working fine.
$.ajax({
type: "POST",
url:'#Url.Action("getResult","Controller")',
data: "{userName :'" + userName + "',password :'" + password + "' }",
contentType: "application/json; charset=utf-8",
dataType: "html",
success: function (data) {
alert("here" + data.toString());
});
This is use for MVC application.
$.ajax({
type: "POST",
url:'getResult',
data: "{userName :'" + userName + "',password :'" + password + "' }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert("here" + data.toString());
});
For Asp.net Application :
$.ajax({
type: "POST",
url:'getResult',
data: "{userName :'" + userName + "',password :'" + password + "' }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert("here" + data.toString());
});
if u have still the issue than please post ur complete code here. i will test and reply soon

What is the equivalent of Ajax.updater in Jquery?

Please let me know the equivalent of below prototype code in Jquery.
var myAjax = new Ajax.Updater('abc', '/billing/add_bill_detail', {
method: 'get',
parameters: pars,
insertion: Insertion.Bottom
});
I want to perform the same action using Jquery.
Thanks in Advance.
In jQuery the Ajax will use as following:
$.ajax({
url: "/billing/add_bill_detail",
type: "get",
dataType: "html",
data: {"pars" : "abc"},
success: function(returnData){
$("#abc").html(returnData);
},
error: function(e){
alert(e);
}
});
Use #abc if abc is the id of the div or use .abc if abc is a class.
You can place the returnData iin your HTML where you want,
There are some ways using ajax like jQuery.ajax({...}) or $.ajax({...}) other than this there are some simplified versions of these too like:
$.get() or jQuery.get()
$.post() or jQuery.post()
$.getJSON() or jQuery.getJSON()
$.getScript() or jQuery.getScript()
$ = jQuery both are same.
As you are using method : 'get', so i recommend you to use $.ajax({...}) or $.get() but remember to include jQuery above this script otherwise ajax function wont work Try to enclose the script in the $(function(){}) doc ready handler.
'abc' if you could explain it
Try adding this with $.ajax():
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$(function(){
$.ajax({
type: "GET",
url: "/billing/add_bill_detail",
data: pars,
dataType: 'html'
success: function(data){
$('#abc').html(data); //<---this replaces content.
},
error: function(err){
console.log(err);
}
});
});
</script>
or with $.get():
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$(function(){
$.get("/billing/add_bill_detail", {data: pars}, function(data) {
$('#abc').html(data); //<---this replaces content.
}, "html");
});
</script>
or more simply use the .load() method:
$('#abc').load('/billing/add_bill_detail');
You can use .load() method
Load data from the server and place the returned HTML into the matched
element.
Read docs: http://api.jquery.com/load/
$(function(){
$.ajax({
type: "GET",
url: "abc/billing/add_bill_detail",
data: data,
success: function(data){
alert(data);
}
});
});

Resources