Ajax success not working for me - javascript

follow code is supposed to show alert msg. It is doing nothing. Can anyone tell me where I am wrong. Everything is working nicely execpt alert().
<script>
$(document).ready(function(){
var baseUrl = document.location.origin;
$(".ProductRemove").click(function(){
var row_id = $(this).attr('id');
$.ajax({
type:"POST",
cache:false,
url:baseUrl+"/shop/api/cart",
data:"row_id="+row_id+"&action=remove", // multiple data sent using ajax
success: function () {
alert('success');
},
error: function(){
alert('failure');
}
});
});
});

Thanks to all,
I got the solution. It is calling error function instead of success because I am returning in nothing from the server.
In ajax empty is not considered as JSON data. So to fix that I have to echo "json_encode(NULL);" in my server.

Related

Why doesn't this function load after a successful ajax call in jquery? (updated)

I'm using the tutorial here, that used to work last month, but now it isn't. I've copied the relevant code below.
<script>
(function($) { //In case jQuery no conflict is being used
$(document).ready(function() { //wait for document ready
$("#loaddaold").click(function () {
alert("123");
//$( "#duplicateshere" ).empty();
$.ajax({
type: "GET",
url: "ajax-oldmessages.php",
dataType: "xml",
success: xmlParser
});
});
});
function xmlParser(xml) {
alert("456");
//$("#rev2").slideDown();
$(xml).find("result").each(function () {
$("#appendhere").append('' + $(this).find("title").text() + '<br>');
//$(".book").fadeIn(1000);
});
}
})(jQuery);
// http://www.webdevdoor.com/jquery/javascript-delay-input-field-change/
// http://papermashup.com/parse-xml-with-jquery/
// (not used) http://www.paulund.co.uk/process-each-node-of-xml-in-jquery
</script>
The problem is that the xmlParser() function isn't being called after the successful ajax request. It shows a 123 alert but not a 456 alert. Am I doing something wrong, or is the tutorial wrong?
Previously on the other question I was told it was a CORS issue, but I was calling the file off my computer, and in my example, so what is the problem now?
if youre using
dataType: "xml"
and if you have an invalid xml in youre response then success wont triger
check youre response because its invalid... if you want to test your code just change
dataType: "html"
and you will see your alert(456) that confirms invalid xml data
I've duplicated your issue and by placing in my response a valid xml, code was running fine
Also if youre expected data is just an string that contains an id, try using
dataType: "xml text"
NOTE: As of jQuery 1.5, jQuery can convert a dataType from what it received in the Content-Type header to what you require

How to send variables with GET without reloading page

What I'm trying to accomplish is the following. I have a php page which loads some variables from an mysql db. Then I want to send these variables using GET to another page without opening the page where the variables are being send to.
At first I really didn't know how to do this until I came across the following:
$( document ).ready(function()
{
$.ajax({
url: 'the_url',
type: 'GET',
data: {Gender:Male,DateOfBirth:1968-07-21},
success: function(data) {
//called when successful
alert("Succes");
},
error: function(e) {
//called when there is an error
console.log(e.message);
alert("Failed");
}
});
}
The $test and $test1 are php variables which I would like to send to the other page. But apparently i'm doing something wrong. Not even the alerts are being triggered so there is probaly something wrong with my syntax.
I'm using the following jquery version: jquery-2.1.4.min.js
If there is something wrong in the way I asked this question please let me know and give me the help to update the question.
Just assign PHP variables to JS variables and also change the data sending part as well there is no need of ' for data sending.
$( document ).ready(function()
{
var test = '<?php echo $test; ?>';
var test1 = '<?php echo $test1; ?>';
$.ajax({
url: 'the_url',
type: 'POST', //change type to POST rather than GET because this POST method of sending data
data: {test:test,test1:test1},
success: function(data) {
//called when successful
$('#ajaxphp-results').html(data);
alert("succes");
},
error: function(e) {
//called when there is an error
console.log(e.message);
alert("failed");
}
});
}

multiple jquery html() assignment not working

I want to show the user a "loader" before and during the ajax call. Here's the code (simplified version...)
$(document).ready(function() {
$("#btn").click(function(){
$("#log").html("loading ajax call...");
anotherFunc();
});
});
function anotherFunc(){
$.ajax({
type: "GET",
url: correct_url,
data: data_to_send,
dataType: "jsonp",
success: function(data){
$("#log").html("new html");
}
})
}
the problem is that "loading ajax call..." never appears. I only see "new html" displayed. the singles ajax #log modification call work perfectly alone (without the other)
is there another way to do?
what am I doing wrong?
ps. I also tryed to write in another id (#log2) with the same result.
Most likely everything works just fine, but the AJAX call returns very quickly (especially if you are testing locally). To see if that is the case, just do the following:
$(document).ready(function() {
$("#btn").click(function(){
$("#log").html("loading ajax call...");
setTimeout(function(){anotherFunc();},2000);
});
});

Jquery form ajax call trouble

I'm having trouble submitting an ajax request.
I've tried to set it up pretty simply just to see if i can get a response
Here is my js:
$(document).ready(function() {
$('#mainform').submit(function() {
$.ajax({
type: "POST",
url: "processform_ajax.php",
data: $(this).serializeArray(),
dataType: "json",
sucess: function (data) {
alert("data" . data);
//$("#response").append(data);
},
error: function(error, txt) {
alert(error.status);
}
});
});
});
My php is simply this
<?php
$errors = array ('a' => 'TEST!');
echo json_encode($errors);
?>
When I try to run this with the firebug extension i'm seeing the post looks okay. (which it shouldn't matter at this point, because my php just echo's out something)
On the response side I'm seeing this error : NS_ERROR_NOT_AVAILABLE
Which leads me to believe it can't find processform_ajax.php, but when i've tried the absolute url in url: "" option above. I can also hit the the php script through the browser's address bar and get the json response
Any clues?
Thanks
NS_ERROR_NOT_AVAILABLE seems like a Firefox "bug/feature" where it tries to submit the call twice.
Try this... add a return false in your code, like this:-
$(document).ready(function() {
$('#mainform').submit(function() {
$.ajax({
...
});
return false;
});
});
This way, once the form is submitted through your JS code, the return false will prevent your "Submit" button from submitting the same request again.
Is sucess a typo in your code, or just on SO?

jQuery getJSON not working

I am trying to get some data back from a server using jQuery $.getJSON, and the code seems to work fine, until it gets to $.getJSON, it doesn't seem to be triggering that at all, there are no console logs when I press the button, here is the code below,
$(document).ready(function(){
var funk;
$('#button').live('click', function(){
var funk = "";
var query = "";
$('#wrapper > [data-custom="field"]').each(function(i, data){
if(i == 0){
funk = query + $(this).attr('id')+" = '"+$(this).val()+"'";
}else{
funk = funk + " AND " + $(this).attr('id')+" = '"+$(this).val()+"'";
};
});
$.getJSON('test.php', {query: funk}, function(json){
console.log(json)
});
});
});
the PHP file test.php in the same folder,
$weo = $_GET['query'];
echo $weo;
Any ideas on what could be causing the problem?
Thanx in advance!
I expect that getJSON is falling over because the server is not returning nice JSON syntax.
Try doing
echo json_encode($weo);
in your PHP file. If you don't ultimately want to use JSON, but plain text instead, use $.get:
$.get('test.php', {query: funk}, function(data){
console.log(data)
});
If you are debugging using:
-> Firefox: open Firebug and look at the Net tab to make sure the request is firing, and to see what the response from the server is.
-> IE: Fire up Fiddler2 to see the request/response.
-> Chrome: use the Resources tab.
Once you see what the server is returning (if anything), you can figure out how to proceed.
For sure your Test.php is not working as expected. To debug what is being returned back from the server try this code
function AjaxDebug() {
$.ajax({
type: "GET",
url: "test.php",
dataType: "jsonp",
data: ({query: funk}),
success: function(results) {
alert("Success!");
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
}); }
Then try having the break point in error and examine the XMLHttpRequest.getresponseText, getresponseXML etc to have a better understanding of what the problem is.
I had the same problem with getJSON not working. I noticed that data gets loaded but is not available to use.
The solution is to use JSONP and in the url querystring add a callback function variable.
$.getJSON("http://www.example.com/test.php?callback=?",function(json){
console.log(json);
});
Note that we put a ? as the callback function name instead of a real function name. This is because jQuery replaces the ? with a generated function name (like jsonp1232617941775) that calls the inline function.
In your PHP you will need to output with the callback function.
echo $_GET['callback'] . '(' . $jsonData . ');';
// prints: jsonp1232617941775({"name" : "Gaurav", "age" : "91"});
This will output valid JSONP object and you will be able to load and use in your jQuery code.

Categories