So yesterday, I added some Jquery code and it worked perfectly. Today I was adding some more for a new part of my website and it did not work. When I tried the code I added yesterday, that stopped working as well. The first thing I do is create a function to get anything from the url that I need. The first 2 inputs are for following users. The first input should send the id variable to the url bar and is retrieved in the php file called follow.php. The second input should do the same thing. Finally the last function is for liking peoples posts. It sends the type of like(like or unlike) to the php file named like.php and is retrieved there. And should post the retrieved data into a div called likes. However, none of which is occurring when the buttons are pressed. Even when I just send an alert to make sure the on click is working, nothing happens either.
Here is my code:
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
$('input#sub').on('click', function(){
var id = getParameterByName('id');
$.get('follow.php' , {id: id}, function(data){
location.reload();
});
});
$('input#sub1').on('click', function(){
var id = getParameterByName('id');
$.get('unfollow.php' , {id: id}, function(data){
location.reload();
});
});
function doAction(postid , type){
alert("Works");
$.post('like.php' , {postid: postid type: type} , function(data){
$('div#likes').text(data);
});
}
Let's try to sum things up. I'm gonna change most of your code simply because you don't need all of that, otherwise jQuery wouldn't be helpful at all.
Assuming your caller is this anchor:
<img id="like" src="Social/down.png"/>
After this you can manipulate the clicked object getting its attributes easily through:
$('.idsfromdb').click(function(){
var id = $(this).prop('id');
var another_id_obj = $('newselector').prop('id');
// more logic, ajax,...
});
You can attach this kind of functions to every click event and then manipulate the object, call a php file, and so on... I hope I helped you somehow with this.
open google developer tools > network and see if request is made and if it has all data you want as request and if there is anything in response.
if there is request with all parameters, you have problem on server side,
if parameters not same that you are trying to send with ajax, than prevent buttons default action, you must prevent it every time when using ajax especially when button submits form.
$('input#sub').on('click', function(event){
event.preventDefault();
//your ajax
}
Related
I am using the below code to get all the names of the checkboxes and passing them to download a file from the server, before my edited code i was using window.location.href and it was working well but with few checkboxes, if i send like 400+, it throws an 500 error
here is my code
jq(document).on('click','#downloadAnsdoc',function() {
var checkedVals = jq('.allchecks:checkbox:checked').map(function() {
return this.value;
}).get();
checkedVals.join(",");
var iframe = $("<iframe/>").attr({
src: 'doc/fetch.cfm?action=catAnsDownload&tx_ID='+checkedVals,
style: "visibility:hidden;display:none"
});
});
and my previous code was
jq(document).on('click','#downloadAnsdoc',function() {
var checkedVals = jq('.allchecks:checkbox:checked').map(function() {
return this.value;
}).get();
checkedVals.join(",");
location.href = 'doc/fetch.cfm?action=catAnsDownload&tx_ID='+checkedVals;
});
the above code was working but passing a big list was creating a problem.
now to solve this, i am trying to send the data as post and make an call to an iframe so it pass all the ids to the database and bring the records and download through an iframe, but my changed method, when i click my button, nothing happens, it does not display any kind of issue, not it does anything
Iam trying to post an Javascript Object via php, but i cant get the value in PHP, iam using laravel framework.
my array,
[type: "sadf", level: "sadfasdf"]
javascript code,
var data_push = Array();
$('form').on('change', 'select, textarea, input', function(t,s){
var key = $(this).attr('id');
var value = $(this).val();
data_push[key] = value;
});
$("#submit").click(function(){
$.post("{!! URL::to('test') !!}", {
_token : tempcsrf,
req_data : data_push
},
function (resp, textStatus, jqXHR) {
alert(resp);
});
});
php code,
public function workbook_save(Request $request_data)
{
$require_data = $request_data->req_data;
print_r($require_data);
}
Tried also JSON.stringfy(data_push) ,json_decode but no luck, i cant get the Javascript object in php, donno what iam doing wrong here, pls advice.
This is what your JS does:
Creates an array
Sets up an event handler to populate the array when things change in the form
Posts the (empty) array to the server
Later on, things will change in the form and data will be put in the array.
The server knows nothing about this because you already sent its contents.
You need to change your logic so you only make the POST request when you are ready to send the data.
I'm doing a webapp with html+jquery and a java rest-service backend.
I have a textfield, with typeahead suggestions, so every character the user types in the field
will trigger a server-round trip and update the list of typeahead suggestions.
Essential parts of the code:
var showTypeaheadSuggestions = function(data) {
// update ui-element ...
}
var displayFailure = function() {
// update ui-element ...
}
var searchText = $("#searchText");
var searchTextKeyup = function() {
var txt = searchText.val();
$.ajax({
url : typeaheadUrl(txt),
type : 'GET',
dataType : 'json',
}).done(showTypeaheadSuggestions).fail(displayFailure);
}
searchText.on('keyup', searchTextKeyup);
It's basically working.
But I was thinking abt what happens if you type, for example, 2 letters "ab" (that will trigger first a request for "a" and then a request for "ab")...
Then, what happens if the "a" response takes a bit longer to process, and arrives after the "ab" response?
Do I need to detect this in my code, to throw away the "a" response?
In http://api.jquery.com/jquery.ajax/ it does says:
Promise callbacks — .done(), .fail(), .always(), and .then() — are
invoked, in the order they are registered.
What does that mean exactly?
I was hoping this means $.ajax() would automatically handle the above scenario correct.
But when I do a small test (on the server-side I simply injected a 2 secs sleep-delay, only when the search-string is exactly "a"),
it turns out it does not behave as I expected.
The typeahead list will first get updated with the "ab" response, and then when the "a" response
arrives, it also updates, so the typeahead list gets the wrong suggestions.
What is the established way to handle this correctly?
There's another approach if you want to keep the server side code without changes. You can actually wrap the return functions inside a class and create instances for each request, then store the latest instance in a global scoped variable and check if the owner of the invoked method does match the latest instance:
var lastRequest;
var searchText = $("#searchText");
function requestClass()
{
var that = this;
this.showTypeaheadSuggestions = function(data) {
//Update ui-element
if (lastRequest == that)
console.log('suggestions retrieved: ' + data);
else
console.log('this response (' + data + ') is ignored');
};
this.displayFailure = function() {
//Update ui-element
console.log('failure');
};
}
var searchTextKeyup = function() {
var request = new requestClass();
lastRequest = request;
var txt = searchText.val();
$.ajax({
url : typeaheadUrl(txt),
type : 'GET',
dataType : 'json',
}).done(request.showTypeaheadSuggestions).fail(request.displayFailure);
}
searchText.on('keyup', searchTextKeyup);
I have tested this with the small-test you proposed in the question (adding a 2 seconds delay when the search string does match the 'a' character) and the result is the following:
suggestions retrieved: ab
this response (a) is ignored
One of the ways I approached this problem was to assign an ID for each time you call it, and pass it as an ID to server side. When your server is done processing it, it then sends the result back along with it's id.
Then, every time the client side code runs, the ID will increment. For example:
var callback_id = 0;
var searchText = $("#searchText");
var searchTextKeyup = function() {
callback_id ++;
var txt = searchText.val();
$.ajax({
url : typeaheadUrl(txt),
data : callback_id,
type : 'GET',
dataType : 'json',
}).done(showTypeaheadSuggestions).fail(displayFailure);
}
searchText.on('keyup', searchTextKeyup);
Then, when you receive the response back, you check if the id is the current one. In the event that the user fires two events at once, your ajax event will be triggered twice, once with callback_id = 0, and one with callback_id = 1.
The last thing you have to then do is an if statement only updating your TypeaheadSuggestions if the callback_id is the most current one by comparing the id sent back from your server response.
You must compare new input text with text you sent, and if it what user wants to find - you will show it, otherwise do nothing with response.
For example :
var searchText = $("input").val()
$.ajax({
....
data: {searchText : searchText}
success: funtion(){
if($("input").val()==searchText){
//SHOW RESULTS
}
}
})
The Promises interface returns to you a "Promise object" immediately so that you can use a different syntax for the callback.
Instead of:
asyncCall(callback);
You can use:
asyncCall()
.then(callback);
And you can chain these:
authorizeAccount()
.then(getNames)
.then(processNames);
The callbacks will be executed in the order you register them -- processNames will wait for getNames to resolve first.
The "established" way to handle this "correctly" is probably to add some client-side debouncing so that only the whole request ('query' instead of 'q', 'qu' 'que'...) is processed when you are typing the word:
http://underscorejs.org/#debounce with a timeout that expires a response if it takes too long to come back.
$('#submit').click(function(){
window.location.replace("searchscreen.html");
var term = $('#search').text();
displaySearchEntries(term);
});
I am writing code to direct to a search results page and to call the javascript function to return the appropriate results. As of now, this redirects the page, and displaySearchEntries(term) gets called, but disappears immediately. It seems as if the redirect happens after the call to the function, but I don't know why that would be happening or how to prevent it. Any suggestions?
You can not control the next page. Once the redirect happens, that page is done.
If you want something to happen on the next page you will need to find a way to pass info to that page. That is normally done with a querystring, posting a form, cookies, or local storage. The next page would need to look for that data and process it.
Basic idea using querystring:
First page:
$('#submit').click(function(e){
e.preventDefault();
var term = $('#search').text();
window.location.replace("searchscreen.html?search=" + encodeUriComponent(term));
});
and code on the searchscreen.html
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
$(function(){
//read querystring
var term = getParameterByName("search");
//run your search
if(term.length) {
displaySearchEntries(term);
}
});
Call function on the redirected page.In search screen.html use document.ready
When you use window.location it kills all the scripts running in the browser. You can use JQuery AJAX call and use the callback function to do the rest.
If you don't won't to use the AJAX function the only possible way to do this is use a parameter to identify the redirection.
window.location = "searchscreen.html?redirect=true";
And check the redirect variable and call the function in the $(document).ready().
I have two HTML pages that work in a parent-child relationship in this way:
The first one has a button which does two things: First it requests data from the database via an AJAX call. Second it directs the user to the next page with the requested data, which will be handled by JavaScript to populate the second page.
I can already obtain the data via an ajax call and put it in a JSON array:
$.ajax({
type: "POST",
url: get_data_from_database_url,
async:false,
data: params,
success: function(json)
{
json_send_my_data(json);
}
});
function json_send_my_data(json)
{
//pass the json object to the other page and load it
}
I assume that on the second page, a "document ready" JavaScript function can easily handle the capture of the passed JSON object with all the data. The best way to test that it works is for me to use alert("My data: " + json.my_data.first_name); within the document ready function to see if the JSON object has been properly passed.
I simply don't know a trusted true way to do this. I have read the forums and I know the basics of using window.location.url to load the second page, but passing the data is another story altogether.
session cookie may solve your problem.
On the second page you can print directly within the cookies with Server-Script tag or site document.cookie
And in the following section converting Cookies in Json again
How about?
Warning: This will only work for single-page-templates, where each pseudo-page has it's own HTML document.
You can pass data between pages by using the $.mobile.changePage() function manually instead of letting jQuery Mobile call it for your links:
$(document).delegate('.ui-page', 'pageinit', function () {
$(this).find('a').bind('click', function () {
$.mobile.changePage(this.href, {
reloadPage : true,
type : 'post',
data : { myKey : 'myVal' }
});
return false;
});
});
Here is the documentation for this: http://jquerymobile.com/demos/1.1.1/docs/api/methods.html
You can simply store your data in a variable for the next page as well. This is possible because jQuery Mobile pages exist in the same DOM since they are brought into the DOM via AJAX. Here is an answer I posted about this not too long ago: jQuery Moblie: passing parameters and dynamically load the content of a page
Disclaimer: This is terrible, but here goes:
First, you will need this function (I coded this a while back). Details here: http://refactor.blog.com/2012/07/13/porting-javas-getparametermap-functionality-to-pure-javascript/
It converts request parameters to a json representation.
function getParameterMap () {
if (window.location.href.indexOf('?') === (-1)) {
return {};
}
var qparts = window.location.href.split('?')[1].split('&'),
qmap = {};
qparts.map(function (part) {
var kvPair = part.split('='),
key = decodeURIComponent(kvPair[0]),
value = kvPair[1];
//handle params that lack a value: e.g. &delayed=
qmap[key] = (!value) ? '' : decodeURIComponent(value);
});
return qmap;
}
Next, inside your success handler function:
success: function(json) {
//please really convert the server response to a json
//I don't see you instructing jQuery to do that yet!
//handleAs: 'json'
var qstring = '?';
for(key in json) {
qstring += '&' + key + '=' + json[key];
qstring = qstring.substr(1); //removing the first redundant &
}
var urlTarget = 'abc.html';
var urlTargetWithParams = urlTarget + qstring;
//will go to abc.html?key1=value1&key2=value2&key2=value2...
window.location.href = urlTargetWithParams;
}
On the next page, call getParameterMap.
var jsonRebuilt = getParameterMap();
//use jsonRebuilt
Hope this helps (some extra statements are there to make things very obvious). (And remember, this is most likely a wrong way of doing it, as people have pointed out).
Here is my post about communicating between two html pages, it is pure javascript and it uses cookies:
Javascript communication between browser tabs/windows
you could reuse the code there to send messages from one page to another.
The code uses polling to get the data, you could set the polling time for your needs.
You have two options I think.
1) Use cookies - But they have size limitations.
2) Use HTML5 web storage.
The next most secure, reliable and feasible way is to use server side code.