Why does my AJAX call return <\/button> instead of </button>? - ajax

my AJAX call is
function xml_getsitepage($idsite){
$.ajax({
url: 'public/xml/xml_getsitehtml.php',
dataType: 'JSON',
data: {
"id":$idsite
},
type: 'POST',
success: function (response) {
$("#nav").html(response.nav);
}
});
return;
}
The last few lines of 'public/xml/xml_getsitehtml.php' are
$arr['htmlnav']=$htmlnav;
$arr['htmlcontain']=$htmlcontain;
$arr['isOK']="Is OK";
}else{
$arr['htmlnav']='Failed1';
$arr['htmlcontain']='Failed1';
}
}else{
$arr['htmlnav']='Failed2';
$arr['htmlcontain']='Failed2';
}
echo json_encode($arr);
exit;
The firebug response tab shows all as "</button>"
where the JSON tab shows them correctly
I have search the web but cannot find anything to help me.
I cannot "see" the data in my browser and the #nav remains blank but if I manually place the html with the \ removed it displays OK.

By default, PHP's json_encode will escape / characters in strings.
This:
Does not change the data. "\/" and "/" are two different, but valid, and equal, JSON representations of a / character.
Lets you use the output as a JavaScript literal, inline in an HTML document, without </script> ending the script element in the middle of the string.
Whatever your problem is, it has nothing to do with the escaped slashes.
If it was, then your generated HTML would have some invalid end tags in it, which would be ignored or treated as text. So you would get more text content in your button then you intended.
Your problem is this mismatch:
$arr['htmlnav']=$htmlnav;
response.nav
You are writing to htmlnav but trying to read from nav.

Slashes are being escaped. Simply unescape the string once you receive it on the front-end.
Or if you're feeling lazy, you can disable the escaping function in the PHP script:
echo json_encode($arr, JSON_UNESCAPED_SLASHES);

Related

not able to pass the selected values through Ajax

This is the script i use for the drop down in the echo table
The echo table
Try passing your data object as text
JAVASCRIPT
$.ajax({
type: "POST",
url: "data.php",
data: JSON.stringify(data1) // use JSON.stringify();
});
Also a note is to make sure your html is echo'd or rendered out before you attempt to bind a javascript function to it. Other wise you will get an error indicating no such html element found.

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

My ajax request isn't working

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
});

external page is not loading inside a div with ajax function whilw posting json code in a variable

I want to load a javascript code inside a div with ajax for this i am doing in this way
$(".pagination_btn").click(function(){
var start = 20;
var json = '{"offer":[{"city_id":"55","city":"Melbourne","name":"Space Hotel","address":"380 Russell St","price_no_vat":"250.96","currency":"AUD","type":"hotel","description":"The 3-star Space Hotel in Melbourne"}]}';
$.ajax({
type:"POST",
url:"search_result.php",
data: "start="+ start +"&json="+ json,
success: function()
{
$('#search_result_cont').load("search_result.php");
}
});//ajax ends
}); // click function ends
what i am doing here is i am posting one start value and json code into variables named start and json and that i want to load into a div#search_result_cont. but when i click in button it show me the blank page. may be my method is wrong for loading the page inside div.
data: {start: start, json: json}
you need to construct data to be sent as an object . . . . same is the case for your json data which has to be encoded as a javascript object
like
json: {name: 'something', address: {street: 'xxx', city: 'yyy'}} etc
Apart from that, can you share the php code of search_result.php . . .
if the php file does not contain any html elements . . .it will be blank since it has nothing to display ........

jQuery 1.5.2 displays [object XMLDocument] for empty responses

I have a Url from which I can get a string
If the response string contains something, everything goes well, but (god forbid!) if the result would be an empty string like "" jQuery 1.5.2 will display it as [object XMLDocument]
follow the codes plz :
$.post('/Applicant/RequestedJob/IsThereActivePeriod',{},
function(data){
if(data == '' )
{
//do something here!
}
else
{
console.log(data.toString());
// [object XMLDocument] will be printed in console.
}
});
Perhaps I should mention that it used to work perfectly on jQuery 1.4.4
any idea?
Regards :)
You should set the expected dataType of the response in your ajax call, like this:
$.post('/Applicant/RequestedJob/IsThereActivePeriod',{},
function(data){
if(data == '' )
openDialog('/Applicant/RequestedJob/AddRequestedJobWindow','pnlRequestedJob','Request Window');
else
{
msgbox.show(data.toString(),'Error', msgBoxButtons.okOnly);
console.log(data.toString());
}
},
'html'
);
Without this, jQuery tries to infer the response type, according to this:
Default: Intelligent Guess (xml, json,
script, or html).
With no returned content, it's apparently guessing XML. By passing it 'html' as the dataType, you force jQuery to interpret the response as HTML, and store the result in plain text.
As per some of the comments, an appropriate content-type header should allow jQuery to infer that your empty string is HTML, achieving the same result without setting the expected dataType explicitly in the ajax call.
The reason you get [object XMLDocument] is because data is an XML document object, and its toString() is being called.

Resources