Permanently print ajax reply with JavaScript/jQuery - javascript

Context
Ajax code is used to fetch data from an Sql database, so when a new message is inserted into a database that message is printed into a HTML div.
The Problem
The problem is that when the variable is inserted into the div, it replaces the existing value of the div. One possible solution is too send the whole chat log every time, however I would prefer to avoid this for obvious reasons!
Client Side Code
var newmessages = function () {
setTimeout(newmessages, 5000);
var request = $.ajax({
url: "ajaxtesting.php",
type: "GET",
dataType: "html"
});
request.done(function(msg) {
if(msg !== null && msg !== "") {
$("#chat").html(msg);
scroll();
}
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
}
The message variable is used to store the Ajax response and the line:
`$("#chat").html(msg);`
Is used to print the value to the div "chat".

Try
$("#chat").append(msg);
If you need to insert new message in top then
$("#chat").prepend(msg);

You need to append to #chat rather than using html().
http://api.jquery.com/append/

You might want to check out jQuery's append() function: http://api.jquery.com/append/
This way you can append the result of the Ajax call.

Related

How to get checkbox value in AJAX

I want to get the value of my checkbox in Ajax so that I can save it in database as a preference for each of my user. I've never done AJAX before so i'm quite lost about it.
My javascript file :
$(document).ready ->
E.accounts.changeUnmarkVisibility()
$('#letters-visibility').on 'click', (e) ->
E.accounts.changeUnmarkVisibility()
$('#label-letters-visibility').on 'click', (e) ->
if $('#letters-visibility').is(':checked')
$('#letters-visibility').prop('checked', false)
else
$('#letters-visibility').prop('checked', true)
E.accounts.changeUnmarkVisibility()
$('#letters-visibility').on 'change', (e) ->
$.ajax
url: "/backend/accounts/{#id}"
type: 'POST'
data:
isChecked: $('#letters-visibility').is(':checked')
success: (data, status, request) ->
console.log data
E.accounts =
changeUnmarkVisibility: ->
unmarkLines = $('.active-list .unmark').closest('tr')
if unmarkLines.is(':visible')
unmarkLines.hide()
else
unmarkLines.show()
)
My post request send me back a 404 error, I think the error is in my 'Data' option
Yeah Deckerz is right normally you have an ajax call which has a 'Data' option and then a success option. The data is an array/object of values that you want to send.
There are lots of options on the jquery ajax page and it's quite easy to get lost in them. This though is the norm. Done is called after some.php (in this case) has finished and msg has the data that is sent back from msg. Normally you'll want this in a json format. This is good practise for if you want to send back 2 variables. e.g Status (success/error) and ErrorMessage = ""
if you're using php json_encode is the function to use to achieve this.
$.ajax({
method: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
I'm not sure I've understood where you're stuck at: it seems to me you've already read the checkbox's value without problems, so I'll assume you don't know what to do with the AJAX call.
The AJAX call is really just a request to your server: you probably want to call a script (pointed to by the URL you pass), with the parameters you need to identify the user and the option, that writes the checkbox's value to the database.
One thing that may be useful to know: you don't need to construct a query string to pass your parameters along with a GET request, you can just pass them in the data parameter of the jQuery.ajax call as a regular JSON object.
AJAX doesn't do that. AJAX returns the value. And then you look at the value to decide what to check. If you are doing this in jquery, then look here: https://api.jquery.com/checked-selector/

PHP code and JQuery within onclick event [duplicate]

I have a link, which links to domain.com , when a person clicks, I want it to do an ajax call to counter.php and post 2 variables to it, so it can add 1 to the views for that link.
I have a link:
Link Title
How would I do this with jquery?
EDIT:
I tried something like this
function addHit(str, partNumber){
$.get("counter.php", { version: str, part: partNumber })
}
It seems to work, but in firebug, the request never completes... it just does that "working..." animation. counter.php echos out some text when its done (doesnt need to show up anywhere).
From the jQuery documentation: http://api.jquery.com/jQuery.ajax/
function addHit(data1, data2)
{
$.ajax({
type: "POST",
url: "http://domain.com/counter.php",
data: "var1=data1&var2=data2",
success: function(msg){
alert( "Data Saved: " + msg ); //Anything you want
}
});
}
You need to add a callback on success
function addHit(str, partNumber){
$.get(
"counter.php",
{
version: str,
part: partNumber
},
function(data){
alert("Data Loaded: " + data);
})
)};
In the case of an anchor, you're leaving the page, so firebug's going to show some weird behavior here as it thinks execution would stop. Unless you're also preventing the default event behavior of the anchor...you're leaving the page and the request (in firebug's view) is discarded.

Can ajax call on return add new javascript function to the page?

I have a jQuery ajax call that returns html of a table. Now I need to let user to do some javascript action on the table.
Can the return ajax response contain the javascript code or do I have to load the javascript code in the page on the first load of the page?
The user has the option of triggering the 'new' javascript. It doesn't have to triggered on ajax call.
To answer the actual question, the return response can contain the script. Simplest is to place it after the html, as the ready event has already fired in page it is being loaded into
You can use the success (or other event) callbacks provided with jQuery .ajax() to perform this JS action. Something like this:
$.ajax({
success: function(){
// Perform JS action
}
}
The jQuery API lists all such event callbacks available for AJAX calls. Check this for more info.
The returned ajax response can contain javascript code as a string. Then you can eval(response).
If you want to request a script with ajax that will be run when retrieved, then you can use jQuery's getScript() method to retrieve it and then execute it.
Per the jQuery doc, getScript() is a shorthand for:
$.ajax({
url: url,
dataType: "script",
success: success
});
Which shows that jQuery's ajax command will handle a returned script for you automatically if you set the data type appropriately.
You can make your request a variable and extend upon it after the set up.
// Make the request to the server
var dataID = $("#WhatINeedForAParameter").val();
var request = $.ajax({
url: "PageOrControllerOrWebApi/MethodName",
type: "POST",
data: { id : dataID },
dataType: "json"
});
// When the request is done process
// what you need done
request.done(function(msg) {
alert('You got this ' + msg);
});
// If the request failed you can
// see what the problem was and
// handle the situation accordingly
request.fail(function(jqXHR, textStatus) {
alert( "Your request failed: " + textStatus );
});
you can do it using success callback i think this can be a way please try
$.ajax({
.....,
.....,
success:
var script = document.createElement( 'script' );
script.type = 'text/javascript';
script.src = url;
$("#tableID").append( script );
});
i hope it should help.

$.ajax JSON not passing values on complete

I'm having an annoying issue, on complete i get undefined when trying to make simple url validation. success working fine.
i get a valid json response:
{"error":"some error"}
and this is my jQuery
$("#myform").submit(function(){
dataString = $("#myform").serialize();
$.ajax({
type: "GET",
url: "myform.php",
data: $.URLDecode(dataString), //fixing url problem
dataType: "json",
beforeSend: function(){
$('#search').append('<img src="images/ajax-loader.gif" />'); //loader
$('.error').remove(); //removes every submit
},
success: function(data){
$('<span class="error">' + data.error + '</span>').appendTo($('#search'));
},
complete: function(data){
$('#search img').fadeOut(); //removes loader
alert(data.error);
}
});
return false; //force ajax submit
});
Any hint please?
If you look at the docs:
complete(XMLHttpRequest, textStatus)
A function to be called when the
request finishes (after success and
error callbacks are executed). The
function gets passed two arguments:
The XMLHttpRequest object and a string
describing the status of the request.
This is an Ajax Event.
Data is not a return value from your method.
If you're using firebug, use console.log(XMLHttpRequest) and you'll see what it includes.
You can also do this (quick - using eval here - not recommended.)
var err = eval("(" + XMLHttpRequest.responseText + ")");
alert(err.Message);
As per the docs, the complete event doesn't hold your json response.
Why do you need to define the complete handler and the success handler? Just define success.
maybe $.URLDecode() returns not JSON key/value structure
I think you want URLEncode not URLDecode? Either way I'd recommend fiddler for debugging issues like this - it'll show you exactly what's being sent to/from the server.

how to execute ajax output script

I'm getting an ajax output success data.
Where the data contains some html text and a script.
But the script is not executing, how can I execute the script.
Let's say Ajax response obj is
<div>something....</div><script>alert("test");</script>
the above code is my Ajax response.The div is getting rendered, but the alert is not working.
Assuming you are not using JSON or jQuery, or any other library, and your AJAX call returns some HTML and/or javascript which is being added to your existing document (eg. using innerHTML), any javascript returned using AJAX will not execute in the browser - except for events on elements in the HTML.
So if your AJAX call returns <input type="button" value="Click me" onclick="alert('hello');" />, the js alert will work ok, but if your AJAX call returns <script type="text/javascript">alert('hello');</script> it will not execute. In that case, you would have to parse the result to extract the javascript and execute it, using a function such as this:
function extract_and_execute_js(output_to_parse)
{
if(output_to_parse != '')
{
var script = "";
output_to_parse = output_to_parse.replace(/<script[^>]*>([\s\S]*?)<\/script>/gi, function(){if (output_to_parse !== null) script += arguments[1] + '\n';return '';});
if(script)
{
if (window.execScript)
{
window.execScript(script);
}
else
{
window.setTimeout(script, 0);
}
}
}
}
If you are retrieving the JSON formatted result from AJAX call, you can just use eval to execute the javascript.
Assume, if the result json is formed like this
var res = '{"Data": "<something>",
"script": "alert(something)"}';
var out = eval("(" + res + ")");
var data = out.data;
eval(out.script);
Interestingly enough, I use jQuery and using the html() function was enough to get the JavaScript to execute. So more or less I had nothing special to do.
There is a simplified version:
var myform = $('form#form-id');
$.post(myform.attr('action'), myform.serialize(), function(response) {
$('#some-id').html(response.message);
}
In my case the code kicked in automatically so I did not need any other of the solutions proposed here.
Not sure if you are using a library, but with Prototype I had to set
evalScripts: true
before JavaScript would be eval-ed. See here for more info:
http://www.sergiopereira.com/articles/prototype.js.html#UsingAjaxRequest
Using jQuery here is a simple bit of code:
$.ajax({
type: "POST",
url: "getData.asmx/HelloWorld",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(result) {
alert(result);
}
});
But, to actually use the results of the variable result I ended up using a javascript library, from http://www.json.org/js.html, I did:
success: function(result) {
var myData = JSON.parse(result.d);
There are probably better approaches, but this was simple, and worked for me, so I just use this. Later, when the project is in production I may go back and clean this up, but that is after I get everything working.

Categories

Resources