I'm trying to get the JSON from this URL into variable
This bit of code successfully puts it in a div element
$("#siteloader").html('<object data="MYURL">');
But I want the contents of that div inside a string variable rather than in the div.
I've also tried the following:
$.ajax({
type : "GET",
dataType : "jsonp",
url : "MYURL", // ?callback=?
success: function(data){
// do stuff with data
}
});
But this shows a syntax error "Uncaught SyntaxError: Unexpected token : " "getfixes:1" in the javascript console when I try it in chrome.
Is it possible for me to just get the contents of a URL as a string in the data variable?
there is a external library according to this post: String URL to json object
http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
Related
I have an ajax script where I am trying to pass the current URL with $_SERVER['PHP_SELF']
var url = encodeURIComponent('<?=$_SERVER['PHP_SELF']?>');
$.ajax({
type: 'post',
url: '/dir/file.php',
data: {url: url},
success: function (data) {
...
}
})
At first, I was trying to pass the URL as is, but I was getting an error and I read that I need to use encodeURIComponent in Javascript first to format the URL.
%2Fsome%2Furl%2Findex.php
Then on the PHP side I am using rawurldecode($_POST['url']); to convert the URL back to normal which then looks like this.
/some/url/index.php
The issue is that I need to put the formatted URL into a variable like so:
$url = rawurldecode($_POST['url']);
But this produces a 500 on my page. If I do echo rawurldecode($_POST['url']); this works and returns the formatted URL.
How do I capture the formatted URL and put it into a variable?
Long story short, I have a textarea and I want to preserve the formatting with the proper line breaks. I'm getting the value of the text area with the following javascript call.
var letterText = document.getElementById("cnl-lettertext").value;
After that I sent it through an Ajax call and rest api to be saved to a database. I can't seem to get it to keep the \r\n characters or line breaks in the variable for some reason when I'm setting it.
I've tried setting white-space: pre on my css for it but that doesn't seem to work. I also don't want to just use .replace because that disrupts other functions.
ajax call:
$.ajax({
url : url, //url is built dynamically for a rest api.
timeout : 5000,
dataType : "json",
statusCode : { },
success : function(data) {
}
});
When you send a request to a URL with line breaks, the browser will remove those line breaks, which are not URL-compatible. They need to be encoded.
You could do it manually with encodeURIComponent, but since you're using jQuery, take advantage of it, and pass query parameters the right way, with the data option. They will be encoded correctly by jQuery:
$.ajax({
url : 'https://www.example.com/endpoint', // don't add query params here
timeout : 5000,
dataType : "json",
data: { // Add them here, they will be encoded automatically
letterText: letterText,
// ...
},
statusCode : { },
success : function(data) {}
});
I was trying to make an ajax call and show an html part inside a div class. For that i used the following way.
$.ajax({
type: "get",
url: "{{url('searchByCheckbox')}}",
dataType: 'html',
success: function(html)
{
$(".infinite-scroll").html(html)
}
});
But the problem is there is a script inside that html part which i wanted to load when i make first ajax call it's not loaded but for the second one it's loaded the script.
suppose the html response like this :
<script>
alert()
</script>
// html
How do i make it work?
I put the script above the html page which i'm getting as response.
(those who are marking the Question as duplicate should read at least what i want and what they wanted )
Im sure that the error is happening because of the script, because you are closing the </script> tag inside the html.
The best solution is to return the data from your ajax call as a json
To do that you should:
1- add a dataType to your ajax parameter as the below:
$.ajax({
type: "get",
dataType: "json",
2- In the php file handling the ajax call, you must resurn the values as a json as below:
Assume that currently you are doing the following:
echo $html
You should change it to match the below:
$retArr = array(
"html" => $html, //Your html code without the javascript function
"jsFunc" => $jsFunc //Your java script function parameters
) ;
echo json_encode($retArr) ;
And then your ajax success must be as the below:
success: function(data)
{ //You can access all the object parametes by calling the object name `data` followed by a dot `.` and then by the parameter key
data.jsFunc // Your javascript function params
$(".infinite-scroll").html(data.html) ;
}
So I am working on something that would allow me to read JSON data from an outside server, and print it out in a more human-readable format. So far I have this:
var address = "example.com";
//not the actual site
$.ajax({
url: address,
dataType: "JSONP",
success: function(data)
{
var obj = JSON.parse(data);
//Misc printing code goes here
},
error: alert("Error")
});
However, I am consistently receiving the error alert.
The console tells me "Unexpected token &". Looking at a few other sources, the issue seems to be that the actual data present on the site is nothing more than raw text.
I changed the dataType field to "text" to try and fix this, but the console error instead changed to tell me that I wasn't allowed access.
I tried retrieving the data and treating it as text with "JSONP text", but it simply returned to the previous "Unexpected token &" error.
Is there any way I can receive text data from an outside server? If not, is there some workaround I could use, such as saving the data to a document and importing it into my code from there?
I have a php returning some json in response to a POST request made via an ajax function.
In my php function I format the data like this:
//json return
$return["answers"] = json_encode($result);
echo json_encode($return);
This returns the following string:
answers: "[{"aa":"Purple","0":"Purple","ab":"Blue","1":"Blue","ac":"Red","2":"Red","ad":"Yellow","3":"Yellow"}]"
And this is where I am trying to catch it to use the data:
$.ajax({
type: "POST",
url: "http://ldsmatch.com/pieces/functions/question.functions.php",
dataType : 'JSON',
data: dataString,
success: function(data) {
alert(data.answers[0]["aa"]);
}
});
I've been trying to just alert the data so I can visualize it before setting up the vars I need, but am having some trouble formatting it correctly so it is usable.
If I alert data.answers[0] then it just shows me the first character in the string, which is a bracket [ and if i subsequently change the number it will go through each character in the returned string.
I have tried other variations, such as:
data.answers[0]["aa"] (this returns 'undefined' in the alert)
data.answers["aa"] (this returns 'undefined' in the alert)
data.answers[0] (this returns the first character of the string)
I feel like I'm close, but missing something. Any guidance appreciated.
edit:
thanks for all the suggestions. I removed the second json_encode and was able to parse with data.answers[0].aa
success: function(data) {
var json = $.parseJSON(data);
alert(json.answers[0]["aa"]);
}
Use parseJson like this
var json = $.parseJSON(data);
$(json).each(function(i,val){
$.each(val,function(k,v){
console.log(k+" : "+ v);
});
});
What if you remove double-encoding on PHP side? You've got an object with JSON string instead of object with first property being object itself, or you may explicitly decode "answers" property on client side as it was suggested above.