jQuery .post() not seeming to work, no error - javascript

I've seen several questions here with the similar subject but I can't find anything which is relevant to my situation. I am trying to build jQuery code that is able to build a list of items to save it in an inventory database and I am using .post() those to a additems.php that will add them to that database (after sensitization), as well as the current path name so the .php can send the user back to the same page.
The behavior I am getting is nothing whatsoever with no console error (except the 'this works' alert when I leave that in.) The behavior I am looking for is, the page should redirect to additems.php as an html form action would, execute the code there and redirect back to this page.
Here is my piece of code:
$(document).ready(function(){
$("#button").click(function(){
alert("this works");
var itemsarray = ['itemname'];
var itemattributesarray = ['itemattribute'];
var quantitiesarray = ['1'];
$.post('additems.php', {
items:{items: itemsarray},
itemattributes:{itemattributes: itemattributesarray},
quantities:{quantities: quantitiesarray},
returnpath: window.pathname
});
});
});
Thank you for your time and any suggestions. I've never used this site so please let me know how I can improve my question as well, if you have the time.

An alternative way is,
$.ajax({
'url':'additems.php',
'method' : 'POST',
'data':{
'items':itemsarray,
'itemattributes':itemattributesarray,
'quantities' : quantitiesarray
},
success: function(data){
//here you will get ajax response
console.log(data);
}
});

Related

document.getElementById(..) gives null even though element is present

I have the following program in which a user can enter any name in a search box after which I redirect the user to a page called usernameSearchResults.php where I print a list of the usernames obtained in the form of an array from usernamesearch.php. Here is the javascript:
$(window).on('load', function() {
$(".searchBarForm").submit(function(e){
e.preventDefault();
var search=document.getElementsByClassName("search")[0].value;
$.ajax
({
type: 'POST',
url: 'usernamesearch.php',
data:
{
search:search
},
success: function (response)
{
window.location.href="usernameSearchResults.php";
response = JSON.parse(response);
var array_length = Object.keys(response).length;//getting array length
for(var i=0;i<array_length;i++){
if(i==0){
document.getElementById("searchResults").innerHTML=""+response[0].username+"<br>";//i=0
}else{
document.getElementById("searchResults").innerHTML+=""+response[i].username+"<br>";
}
}
window.stop();//stops page from refreshing any further(put here to fix a bug that was occuring)
},
error: function(xhr, status, error) {
alert(xhr.responseText);
}
});
return false;
})
});
This is usernameSearchResults.php(inside tags):
<h1>Username Search Results</h1>
<p id="searchResults"></p>
But the problem is that whenever I go to any other page say index.php and enter the username to be searched, the page redirected to is indeed usernameSearchResults.php but the page is blank and error in the console shown says document.getElementById("searchResults") is null.But if I stay at the page usernameSearchResults.php and refresh it and then search any name again, then the results are correctly obtained. What is the problem here?
I would say that the user is being redirected to usernameSearchResults.php but the JavaScript code is still being executed from the current page, which have no element with id "searchResults" defined.
As #Kashkain said, one way to achieve what you want is to pass your response variable in your redirection url and process it then into your other page.
I think the problem here is that the new document could very well still not have been loaded when you call getElementById.
You could add a listener on your target element which would trigger on the load event. In this event's handler you could execute the operations that are now giving you an error.
I have never done or tried this, but maybe something like this would work:
$('#searchResults').on('load', function() {
//execute code here
});
Or you could add a form to the page with action="target_url" method="post" and send your response data through post by doing form.submit, and place the problematic code into usernameSearchResults.php, which will need to read data from POST - this way you can send your ajax data to the new page

AJAX not working occasionally

I am trying to make a chrome extension which fetches IDs of Youtube videos, but am facing a problem. For first execution, the AJAX call gives me an error, but for all subsequent calls, works just fine. This happens every time I open the extension. I am new to the scene, and hence, please excuse me for any rookie mistakes. My code :-
function getIDs(data){
var items = [];
for(i in data.items){
items.push(data.items[i].id.videoId.toString());
}
for(i in items){
$('<p>'+items[i]+'</p><br>').appendTo('#results');
}
}
function getVideo(searchQuery){
searchQuery = searchQuery.replace(/ /g,'+');
var queryURL = 'https://www.googleapis.com/youtube/v3/search?q='+searchQuery+'&key=AIzaSyDq5SqWuQIEfIx7ZlQyKcQycF24D8mW798&part=snippet&maxResults=3&type=video';
$.ajax({
url: queryURL,
dataType: 'json',
success: function(data) {
getIDs(data);
},
error: function(ts){
alert(ts.responseText);
}
});
}
document.addEventListener('DOMContentLoaded',function(){
var button = document.getElementById('search');
var div = document.getElementById('results');
button.addEventListener('click',function(){
var input = document.getElementById('input');
var result = input.value;
getVideo(result);
});
});
I can't for the life of me figure out what is wrong. Thanks for the help in advance.
EDIT
I forgot to mention, but it gives me an undefined error. Sorry !!
I tried your Chrome extension and managed to replicate this behaviour.
The problem is in the following code:
<form action="#">
<input type="text" id="input"><br><br>
<center><button id="search">Click Here!!</button></center>
</form>
Upon clicking the search button, the form is being submitted and reloading the page. The page reloads so your AJAX request is cancelled. This is what what giving you the readyState 0 error. One way you can tell this is happening is by noticing that the text from the text input disappears when you press the button.
To stop the reloading, you could use e.preventDefault() in the JavaScript like the page above suggests, but I think the most appropriate solution here is to add type="button" to your button:
<button id="search" type="button">Click Here!!</button>
You may wonder why this only happened on the first request. This comes down to how action="#" is handled and the answer is basically, not in any standard way that you can rely on. In fact, you can test here and see that Firefox doesn't reload the page at all, whereas Chrome does, but only the first time.
Your problem seems to be that the data you're retrieving doesn't load in time in the first execution since AJAX calls are asynchronous. So when you call getIDs(data), data might not be loaded yet (which is why it's working on the subsequent calls).
One way you can resolve this issue is by using a promise. Rather than using success, you can do something like this:
var ids;
$.ajax({
url: queryURL,
dataType: 'json',
success: function(data) {
ids = data;
},
error: function(ts){
alert(ts.responseText);
}
}).then(function(){
getIDs(ids); //calls this function *after* the data is retrieved
});
This post on StackOverflow does a good job of explaining it.

AJAX not Working on Another Page Correctly

I am working on a social networking site where user Posts are displayed on the home page. They can be liked and commented on. If a post is liked,
it updates the like table through AJAX and have like count incremented by one.
AJAX code:
$(".mlike").click(function () {
$(".murconform").submit(function(e){
return false;
});
var $this=$(this);
var post_id = $(this).val();
var user_id = $(".user_id").text();
alert('Post: '+post_id +' User: '+user_id);
var request = $.ajax({
url: "likes.php",
type: "POST",
data: { post : post_id , user : user_id },
dataType: "html"
});
request.done(function( msg ) {
$this.prev('.likecount').html( msg );
});
});
In the home.php page I have some PHP variables ($userID, $userName) that are data fetched from MySQL and they all work fine but they
don't work with the variables ($viewedUserID, $viewedUserName) in the user.php. In the user.php, only posts related to profile been
viewed are fetched but when you press the like button and try to comment on any of the post it says undefine variables; $viewedUserID, $viewedUserName. And these
variables are defined from the beginning of the page in user.php.
I have been thinking of what might be the possible cause of this and was also thinking the AJAX was suppossed to have effect on the clicked
button only.
NOTE: The alert works just fine.
Thanks in advance.
Was going to write as a comment, but I guess an answer will be clearer:
Ajax
How does AJAX work?
I think you're getting confused with what Ajax's job is. The problem is Ajax is literally just a connector between your front-end (JS / HTML) and back-end (PHP / Rails etc)
Your statements that "Ajax isn't updating MYSQL" lead me to believe you're relying on Ajax to update your table. It won't
Your table will update by using PHP, which is why most of the comments are focused on the PHP & not the JS
PHP
Your Ajax needs to send the correct data to PHP, but then it's your server-side scripts' job to sort it all out, sending a worthy response
Your JS looks like it will work well, but I think your problem will be with your backend. If you update your question with your PHP you'll get a lot more clearer answers!

Ajax call in WordPress causes unwanted page reload and aborts fancybox presentation

A quiz form is completed by the user and the "Score Quiz" link is clicked. What is wanted is for the score to be tallied, results sent to server via jQuery ajax call, and the fancybox presenting the user notice.
What is happening is the tally is done and the ajax call is initiated and the page reloads. If I comment out the ajax call, the fancybox appears as desired. Using Wordpress 3.4.2.
What might be going on?
jQuery('#checkQuiz').click(function(){
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
// tally correct answers
var quizData = tallyScore();
// display user notice
jQuery('a#hiddenAnchor').trigger('click');
// store the data while the user is reading the results display
jQuery.ajax({
type:"post",
url:ajaxurl,
data:quizData
});
return false;
});
NOTE 1: I was able to catch an error in the Firebug console:
NS_ERROR_XPC_NOT_ENOUGH_ARGS: Not enough arguments [nsIDOMLocation.replace]
The file reported is jQuery.js and that appears to be a version 1.7.2. I noted that jQuery current release is 1.8.1. I wonder if that is part of the problem.
NOTE 2: I forgot to mention that this code is part of page template in a child theme. Similar ajax calls made on other pages in the web app work fine. I added a post to the Wordpress.org troubleshooting forum in case someone there doesn't visit stackoverflow.
NOTE 3: I tested this with the standard theme for wordpress "twentyeleven". The same error occurred. I am running out of options to test.
You should try:
jQuery('#checkQuiz').click(function(e){
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
// tally correct answers
var quizData = tallyScore();
// display user notice
jQuery('a#hiddenAnchor').trigger('click');
// store the data while the user is reading the results display
jQuery.ajax({
type:"post",
url:ajaxurl,
data:quizData
});
e.preventDefault()
return false;
});
Using e.preventDefault should stop the page from reloading.
Note that I made two changes to your code. I added e to the parameter-list for your callback function and e.preventDefault at the end of that function.
After testing and decomposing the code involved, the error was found in the data array passed into the ajax call. To aid anyone seeking answers for a similar error here is what I found in the code.
quizData is an array structured for the WordPress ajax handler.
Code As Found
var quizData = {
action: 'save_quiz',
item: invoice_item,
lesson: jQuery("#lesson"),
score: ratio };
There are two problems with this code. First, the jQuery call is assigning a jQuery object to the array value element "lesson". This results in an "undefined" value in the array that creates the error condition. The missing bit here is the ".val()" function invocation.
The second one may be the code architecture of the project, but it appears that a jQuery call within array assembly block does not work as expected. In my tests, the data array contained an empty value.
Resolution
var lesson_id = jQuery("#lesson").val();
var quizData = {
action: 'save_quiz',
item: invoice_item,
lesson: lesson_id,
score: ratio };
I hope this helps someone.

how to use JSON for an error class

Hey all. I was fortunate enough to have Paolo help me with a piece of jquery code that would show the end user an error message if data was saved or not saved to a database. I am looking at the code and my imagination is running wild because I am wondering if I could use just that one piece of code and import the selector type into it and then include that whole json script into my document. This would save me from having to include the json script into 10 different documents. Hope I'm making sense here.
$('#add_customer_form').submit(function() { // handle form submit
The "add_customer_form" id is what I would like to change on a per page basis. If I could successfully do this, then I could make a class of some sort that would just use the rest of this json script and include it where I needed it. I'm sure someone has already thought of this so I was wondering if someone could give me some pointers.
Thanks!
Well, I hit a wall so to speak. The code below is the code that is already in my form. It is using a datastring datatype but I need json. What should I do? I want to replace the stupid alert box with the nice 100% wide green div where my server says all is ok.
$.ajax({
type: "POST",
url: "body.php?action=admCustomer",
data: dataString,
success: function(){
$('#contact input[type=text]').val('');
alert( "Success! Data Saved");
}
});
Here is the code I used in the last question, minus the comments:
$(function() {
$('#add_customer_form').submit(function() {
var data = $(this).serialize();
var url = $(this).attr('action');
var method = $(this).attr('method');
$.ajax({
url: url,
type: method,
data: data,
dataType: 'json',
success: function(data) {
var $div = $('<div>').attr('id', 'message').html(data.message);
if(data.success == 0) {
$div.addClass('error');
} else {
$div.addClass('success');
}
$('body').append($div);
}
});
return false;
});
});
If I am right, what you are essentially asking is how you can make this piece of code work for multiple forms without having to edit the selector. This is very easy. As long as you have the above code included in every page with a form, you can change the $('#add_customer_form') part to something like $('form.json_response'). With this selector we are basically telling jQuery "any form with a class of json_response should be handled through this submit function" - The specific class I'm using is not relevant here, the point is you use a class and give it to all the forms that should have the functionality. Remember, jQuery works on sets of objects. The way I originally had it the set happened to be 1 element, but every jQuery function is meant to act upon as many elements as it matches. This way, whenever you create a form you want to handle through AJAX (and you know the server will return a JSON response with a success indicator), you can simply add whatever class you choose and the jQuery code will take over and handle it for you.
There is also a cleaner plugin that sort of does this, but the above is fine too.
Based on your question, I think what you want is a jQuery selector that will select the right form on each of your pages. If you gave them all a consistent class you could use the same code on each page:
HTML
<form id="some_form_name" class="AJAX_form"> ... </form>
Selector:
$('form.AJAX_form")

Categories