My ajax request isn't working - ajax

I have an <ul id="keuze_lijst"> , an input field with id #sykje and an button with class .search .
Now when i press the button i would like to clear the UL and repopulate it with data, for this i currently got this .js file.
$(document).ready(function() {
$(".search").click(function(){
var searchValue = $("#sykje").val();
$("#keuze_lijst").empty();
$.ajax({
url: 'http://www.autive.nl/frysk/simulator/sim.php?action=getSongs&search='+searchValue,
data: "",
dataType: 'json',
success: function(rows) {
for(var i in rows){
var row = rows[i];
var id = row[1];
var titel = row[2];
var artiest = row[9];
$("#keuze_lijst").append("<li class='mag_droppen'>"+
"<div class='song_left'>"+
"<div class='titel'>"+titel+"</div>"+
"<div class='artiest'>"+artiest+"</div>"+
"</div><!-- .song_left -->"+
"</li>");
}
}
});
});
});
When i remove the ajax command and put something like $("#keuze_lijst").html("hello"); it works fine. But the ajax command isn't working. Though the var searchValue does his work. (ajax uses the correct url). And when i enter that url the page echoes an fine json with multiple rows.
But in my page the ajax script isn't adding the <li>.
What am i doing wrong?
edit: added an jsfiddle -> http://jsfiddle.net/TVvKb/1/

.html() totally replaces the HTML. So at the end, your "#keuze_list will contain </li>.
Just execute one html() command after you build your html into a string var or something.

From a quick glance, I can say that the problem might be with your use of the html() function. This actually replaces the entire html content.
You might want to try using append() or prepend().

Possible Problems:
You are running into a Same Origin Problem. Per default you can only make Ajax-Requests to your own domain. If you need to make cross-domain calls use JSONP or CORS.
Use the html() only once, and hand over your complete string, otherwise you will override your previous html all the time.
You are not landing in the success handler due to an error (e.g. invalid JSON).

Not sure, but I think if you insert a string in the .append() and other jQuery methods, it parses to (valid) HTML first. That means that unclosed tags are closed, making your HTML invalid.
$('<div />'); // parses to <div></div>
So, I assume that your DOM ends up like this this:
$('ul').append('<li>').append('foo').append('</li>'); // <ul><li></li>foo</li></ul>
Please, just format your string first. You don't want jQuery to parse every input.
var str = '<li>';
str += 'foo';
str += '</li>';
$('ul').html(str);
For cross-domain AJAX requests (without JSONP):
proxy.php
header('Content-Type: application/json');
if(empty($_GET['search'])) exit;
$url = 'http://www.autive.nl/frysk/simulator/sim.php?action=getSongs&search=' . $_GET['search'];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_exec($ch);
curl_close($ch);
Javascript
$.getJSON({
url: 'proxy.php&search='+searchValue,
success: callback
});

Related

AJAX response returns current page

I was searching for a similar issue for a while now, but none of the solutions worked for me (and I couldn't find exactly the same issue).
First of all, the website I'm working on is running on Zend Framework. I suspect that it has something to do with the issue.
I want to make a pretty basic AJAX functionality, but for some reason my response always equals the html of the current page. I don't need any of Zend's functionality, the functions I need to implement could (and I'd prefer them to) work separately from the framework.
For testing purposes I made it as simple as I could and yet I fail to find the error. I have a page "test.php" which only has a link that triggers the ajax call. Here's how this call looks:
$('.quiz-link').click(function(e){
e.preventDefault();
$.ajax({
URL: "/quiz_api.php",
type: "POST",
cache: false,
data: {
'test': 'test'
},
success: function(resp){
console.log(resp);
},
error: function(resp){
console.log("Error: " + reps);
}
});
});
And this quiz_api.php is just:
<?php
echo "This is a test";
?>
When I click on the link I get the entire HTML of the current page. "This is a test" can't be found there. I'm also getting an error: "Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check http://xhr.spec.whatwg.org/."
I reckon it has to do with the JS files that are included into this HTML response, but I've also tried setting "async: true" and it didn't help.
I would like to avoid using Zend Framework functions for this task, because I'm not well familiar with it and even making a simple controller sounds rather painful. Instead I want to find out what's causing such behavior and see if it can be changed.
PS: I've also tried moving quiz_api.php to another domain, but it didn't change anything.
I know that it might be an older code but it works, simple and very adaptable. Here's what I came up with. Hope it works for you.
//Here is the html
Link Test
<div id="test_div"></div>
function test(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// This is the php file link
var url = "quiz_api.php";
// Attaches the variables to the url ie:var1=1&var2=2 etc...
var vars = '';
hr.open("POST", url, true);
//Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange =
function(){
if(hr.readyState == 4 && hr.status == 200){
var return_data = hr.responseText;
console.log(return_data);
document.getElementById('test_div').innerHTML = return_data;
}else{
document.getElementById('test_div').innerHTML = "XMLHttpRequest failed";
}
}
//Send the data to PHP now... and wait for response to update the login_error div
hr.send(vars); // Actually execute the request
}
you can change the whole page with a document.write instead of changing individual "div"s

getting a response data in ajax using codeigniter

Hi i have this data which i want that only a certain div will refresh using ajax. How will i able to pass the json_encode to the ajax what will load the data on a certain div using codeigniter.
Heres my controller below
$this->data['getNumberOfMessages'] = $this->mm->getNumberOfMessages($this->data['id']);
$this->data['countNumber'] = $this->data['getNumberOfMessages'];
$responseOnject = new stdClass();
$responseOnject->status = 'ok';
$responseOnject->StatusMessages=$this->data['countNumber'];
$this->output->set_output(json_encode($responseOnject));
this line of code here
$this->output->set_output(json_encode($response));
outputs this one
{"status":"ok","StatusMessages":20}
and i want that to pass through my ajax in my code below
$(document).ready(function(){
var id =$(this).data("messageid");
$.ajax({
type: "get",
url: $(this).data("href"),
success: function(data){
alert(data.StatusMessages);
console.log(data.StatusMessages);
$("#" + id + ' span.badge').html(data.StatusMessages);
}
});
});
and target on my certain div so that it will automatically refresh
below is my code
<tr>
<th>
<a href="#" id="<?php echo $id; ?>" data-messageid="<?php echo $id; ?>" data-href="<?php echo base_url().'profile'?>" title="messages">
<span class="badge"><?php echo $countNumber; ?></span>
message(s)</a>
</th>
</tr>
when i tried to alert(data.StatusMessages);it return undefined.
can someone pls help me figured this thing out? ive been stuck in this.. my code really works but i want to be ajax, only certain div refresh without refershing my entire page.
Any help is muchly appreciated.
You need to decode the response JSON first in order to be able to access it as a JS object. This is how it's done in JS:
JSON.parse(JSONStringHere);
So, your success callback should be:
success: function(data){
data = JSON.parse(data); // this is what decodes JSON
alert(data.StatusMessages);
console.log(data.StatusMessages);
$("#" + id + ' span.badge').html(data.StatusMessages);
}
As I said in the comments, you're not calling the right URL with AJAX (although you said you do and that it returns that JSON string; if so, the code above would work). This doesn't look like it would give you a URL:
$(document).ready(function(){
var id =$(this).data("messageid");
$.ajax({
type: "get",
url: $(this).data("href"), // <---- what is the value of this?
Once you fix that, your code will work.
For JSON data your controller should have the following line to output
UPDATE
Just noticed your problem is that codeigniter is outputting html along side your ajax response.
To Make this go away, Your code in the controller should be like this:
$this->output
->set_content_type('application/json', 'utf-8')
->set_output(json_encode($responseOnject))
->_display();
exit;
This would force the output library to display & the exit to stop displaying anything else.
If you do not set the application/json content type, your response won't be treated as JSON And you'd have to use JSON.parse in your javascript code to convert it to json which is a bad practice.

Ajax send parameters through url

I'm new with ajax and thought i'd be a fun experiment to put into my project. I've created my own lightbox type feature to send a message on a website I'm creating. When the user clicks "Send Message", that's when the lightbox appears, and at the top I'm trying to get it to say "Send message to User", where User is the name of the user they're sending a message too. My lightbox html elements are actually on a seperate webpage, which is why I'm using ajax. this is what I have so far, and can't seem to figure out what the problem is:
user.php page
<div id = "pageMiddle"> // This div is where all the main content is.
<button onclick = "showMessageBox(UsersName)">Send Message</button>
</div>
Note: The username passes correctly into the javascript function, I have checked that much.
main.js page
function showMessageBox(user){
alert(user); // where i checked if username passes correctly
var ajaxObject = null;
if (window.XMLHttpRequest){
ajaxObject = new XMLHttpRequest();
}else if (window.ActiveXObject){
ajaxObject = new ActiveXObject("Microsoft.XMLHTTP");
}
if (ajaxObject != null){
ajaxObject.open("GET", "message_form.php", true);
ajaxObject.send("u="+user);
}else{
alert("You do not have a compatible browser");
}
ajaxObject.onreadystatechange = function(){
if (ajaxObject.readyState == 4 && ajaxObject.status == 200){
document.getElementById("ajaxResult").innerHTML = ajaxObject.responseText;
// use jquery to fade out the background and fade in the message box
$("#pageMiddle").fadeTo("slow", 0.2);
$("#messageFormFG").fadeIn("slow");
}
};
}
message_form.php page
<div id = "messageFormFG">
<div class = "messageFormTitle">Sending message to <?php echo $_GET['u']; ?></div>
</div>
Note: When accessing this page directly through the URL, giving it a parameter of u and a value, it displays correctly
Use jQuery.ajax();
http://api.jquery.com/jQuery.ajax/
$.ajax({
type: "GET",
url: "message_form.php",
data: { name: "John", location: "Boston" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
freakish way to do it (old school) :)
anyway i think the problem may be that you are loading an entire html page to a div! meaning tags and stuff, a good way to understand what's wrong would be to use a debugger and see what comes in ajaxObject.responseText.
Hope this helps.
Btw convert to jQuery ajax!! saves you loads of time =)
I believe that you need to add a request header prior to sending your data. So you'd have this:
ajaxObject.open("GET", "message_form.php", true);
ajaxObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxObject.send("u="+encodeURIComponent(user));
Instead of what you have.
However, it may be a good idea to allow a library to do this for you. It looks like you already have jQuery loaded, so why not let it handle your AJAX requests instead?
I figured it out after watching some ajax tutorials from bucky :) aka thenewboston. If I'm using the GET method, i just had to add the parameter to the end of the url in the .open function, instead of passing it through the send function (like you would a post method).
if you want to send number of field values using ajax.you can use serilalize function.
Example:
jQuery.ajax({
url: 'filenamehere.php',
type: 'post',
data: $("#formidhere").serialize(),
success: function(data){
..//
}
});

Send Multiple data with ajax

I want to use ajax for add data in database and i found following code in net and it is working fine.
<script language='javascript'>
reqObj=null;
function saveCust(){
document.getElementById('res').innerHTML='processing';
if(window.XMLHttpRequest){
reqObj=new XMLHttpRequest();
}else {
reqObj=new ActiveXObject('Microsoft.XMLHTTP');
}
reqObj.onreadystatechange=processSave;
reqObj.open('POST','./custSave?reqObj.open('POST','./cName?id='+document.getElementById('CustCode').value,true);,true);
reqObj.send(null);
}
function processSave(){
if(reqObj.readyState==4){
document.getElementById('res').innerHTML=reqObj.responseText;
}
}
</script>
Above code sends only one String but, i have 5 Strings in my form.
Please anybody alter the code for sending multiple data.
The problem is that you're sending a single parameter in the reqObj.open function:
reqObj.open('POST','./custSave?reqObj.open('POST','./cName?id='+document.getElementById('CustCode').value,true);,true);
Note that the only parameter you send is id.
You can add more parameters in the flavor of QueryString:
id=something&otherParameter=else //and more parameters
IMO the easiest way to handle an ajax request would be using jQuery, as shown and heavily explained by BalusC in How to use Servlets and Ajax?.
Based on the samples there and jQuery Ajax POST example with PHP, you can come with the following code:
Assuming the 5 Strings are in the form
function saveCust(){
$('#res').html('processing');
var $form = $(this);
var serializedData = $form.serialize();
$.post('./custSave', serializedData, function(responseText) {
$('#res').html(responseText);
});
}
Assuming there's data outside the form
function saveCust(){
$('#res').html('processing');
var $form = $(this);
var serializedData = $form.serialize() + "&id=" + $('#CustCode').val();
$.post('./custSave', serializedData, function(responseText) {
$('#res').html(responseText);
});
}
And you can even enhance this using more jQuery functions, but that's outside the scope of this answer.

Cross-Domain Requests with jQuery

For a project I need to get the source code of web page of different other domains.
I have tried following code:
$('#container').load('http://google.com');
$.ajax({
url: 'http://news.bbc.co.uk',
type: 'GET',
success: function(res) {
var headline = $(res.responseText).find('a.tsh').text();
alert(headline);
}
});
Still I am not getting any results but just a blank alert box.
By default all browsers restrict cross-domain requests, you can get around this by using YQL as a proxy. See a guide here: http://ajaxian.com/archives/using-yql-as-a-proxy-for-cross-domain-ajax
For security reasons scripts aren't able to access content from other domains. Mozilla has a long article about HTTP access control, but the bottom line is that without the website themselves adding support for cross-domain requests, you're screwed.
This code is Working Perfectly with the help of JQuery and YQL
$(document).ready(function(){
var container = $('#target');
$('.ajaxtrigger').click(function(){
doAjax($(this).attr('href'));
return false;
});
function doAjax(url){
if(url.match('^http')){
$.getJSON("http://query.yahooapis.com/v1/public/yql?"+
"q=select%20*%20from%20html%20where%20url%3D%22"+
encodeURIComponent("http://www.yahoo.com")+
"%22&format=xml'&callback=?",
function(data){
if(data.results[0]){
var data = filterData(data.results[0]);
container.html(data);
} else {
var errormsg = '<p>Error: could not load the page.</p>';
container.html(errormsg);
}
}
);
} else {
$('#target').load(url);
}
}
function filterData(data){
data = data.replace(/<?\/body[^>]*>/g,'');
data = data.replace(/[\r|\n]+/g,'');
data = data.replace(/<--[\S\s]*?-->/g,'');
data = data.replace(/<noscript[^>]*>[\S\s]*?<\/noscript>/g,'');
data = data.replace(/<script[^>]*>[\S\s]*?<\/script>/g,'');
data = data.replace(/<script.*\/>/,'');
return data;
}
});
The solution for your case is JSON with padding or JSONP.
You will need an HTML element that specified for its src attribute a URL that returns JSON like this:
<script type="text/javascript" src="http://differentDomain.com/RetrieveUser?UserId=1234">
You can search online for a more in-depth explanation, but JSONP is definitely your solution for this.
Do the following steps.
1: Add datatype:jsonp to the script.
2: Add a "callback" parameter to the url
3: Create a javascript function with name same as "callback" param value.
4: The output can be received inside javascript function.
Found one more solution for this :
function getData(url){
if(url.match('^http')){
$.get(url,
function(data){
process(data);
}//end function(data)
);//end get
}
}
This is really a pretty easier way to handle cross-domain requests. As some of the sites like www.imdb.com rejects YQL requests.

Resources