How to simply read html from any url via javascript and proxy? - javascript

This is my proxy.php file:
$url = urldecode($_GET['url']);
$url = 'http://' . str_replace('http://', '', $url); // Avoid accessing the file system
echo file_get_contents($url); // You should probably use cURL. The concept is the same though
and my reader.js:
$(document).ready(function () {
var url = 'http://localhost/taboo.blue-world.pl/admin/proxy.php?url=' + encodeURIComponent('http://www.blue-world.pl')
$.ajax({
url : url,
type : 'GET',
dataType : 'json'
}).done(function(data) {
console.log(data.results.result[1].category); // Do whatever you want here
});
});
But it doesnt print anything. Can you help me solve it? I am not quite good with this.

Currently your are trying to get JSON response. Change dataType to html.
dataType: 'html'

It looks like you are trying to get an HTML response as JSON.
If the content is HTML you should turn you ajax call to:
$.ajax({
url : url,
type : 'GET',
dataType : 'html'
}).done(function(data) {
console.log(data); // data contains the html as a text
});

Use either dataType: 'html' in reader.js (to get HTML data)
OR
echo(json_encode(file_get_contents($url))); in proxy.php (for JSON data)

Try jQuery.parseJSON for json format
$.ajax({
url : url,
type : 'GET',
dataType : 'json'
}).done(function(data) {
var data = jQuery.parseJSON(data);
console.log(data.results.result[1].category); // Do whatever you want here
});
});

Related

Jquery get json data from data type dataString

I have the following jquery function which submits data to the database :
$('#book_client_form').submit(function (event) {
dataString = $("#book_client_form").serialize();
$.ajax({
type: "POST",
url: "<?php echo base_url() ?>operations/book_client",
data: dataString,
success: function (data) {
console.log(data);
$('.job_card_id').val(data[0].id);
$(".info_box_reload").show('slow');
setInterval(function () {
$(".add_new_client_div").hide('slow');
$(".clients_table_div").show('slow');
}, 3000);
}
});
event.preventDefault();
return false;
});
Once the data is supposed to returned the last insert id in json format which gives me the following output :
[{"id":"17"}]
But when I try to pass it to a text field or alert it , I get an undefined output or passes empty. Please advise on how can I pass it to the text input? I'm using datatype : datastring.
did you try parsing the JSON data?
data = JSON.parse(data);
console.log(data[0].id); // you can see the id in the dev console
$('.job_card_id').val(data[0].id);
or you can set dataType : 'jsonp' to get a JavaScript object as response
use dataType, its case sensitive.

pass data($post) to php file using javascript without callback

I need to pass data from HTML page to PHP page But without data callback ....
i'm used two method but One of them did not succeed
1)
$.ajax({
type: "POST",
url: 'phpexample.php',
data: {voteid: x },
success: function(data)
{
alert("success! X:" + data);
}
});
2)
$.post("getClassStudent.php",
{
},
function(data){
$("#div_id.php").html(data);
}
);
as i can understand, you just want to send info to a php script and don't need the response, is that right?
try this
$.post("phpexample.php", {voteid:x});
or simply remove the "succes" function from the equation if you feel more confortable using $.ajax instead of $.post
$.ajax({
type: "POST",
url: 'phpexample.php',
data: {voteid: x }
});
your fisrt example is correct, the second is not well formed.
more info:
http://api.jquery.com/jquery.post/
EDIT: to help you some more :)
<button type="button" id="element-id">click</button>
<button type="button" class="class-name">Click</button>
$(document).ready(function(){
//if you are marking ans element by class use '.class-name'
$(".class-name").click(function(){
$.post("getClassStudent.php");
});
//if marking by id element use '#id-name'
$("#element-id").click(function(){
$.post("getClassStudent.php");
});
});
be carefful with the markings, for debuggin try to use "console.log()" or "alert()" so you can see where is the problem and where the code crushes.
var formData = {
'voteid' : 'x',
};
$.ajax({
type : 'POST',
url : 'phpexample.php',
data : formData, // our data object
dataType : 'json',
encode : true
}).done(function(data) {
console.log(data);
});

codeigniter or PHP - how to go to a URL after a specific AJAX POST submission

I am successfully inserting data into my database in codeigniter via a an ajax post from javascript:
//JAVASCRIPT:
$.ajax({
type: "POST",
url: submissionURL,
data: submissionString,
failure: function(errMsg) {
console.error("error:",errMsg);
},
success: function(data){
$('body').append(data); //MH - want to avoid this
}
});
//PHP:
public function respond(){
$this->load->model('scenarios_model');
$responseID = $this->scenarios_model->insert_response();
//redirect('/pages/view/name/$responseID') //MH - not working, so I have to do this
$redirectURL = base_url() . 'pages/view/name/' . $responseID;
echo "<script>window.location = '$redirectURL'</script>";
}
But the problem is that I can't get codeigniter's redirect function to work, nor can I get PHP's header location method to work, as mentioned here:
Redirect to specified URL on PHP script completion?
either - I'm guessing this is because the headers are already sent? So as you can see, in order to get this to work, I have to echo out a script tag and dynamically insert it into the DOM, which seems janky. How do I do this properly?
Maybe you can 'return' the url in respond function and use it in js
PHP :
public function respond(){
// code
$redirectURL = base_url() . 'pages/view/name/' . $responseID;
return json_encode(['url' => $redirectURL]);
}
JS :
$.ajax({
type: "POST",
url: submissionURL,
data: submissionString,
dataType: 'JSON',
failure: function(errMsg) {
console.error("error:",errMsg);
},
success: function(data){
window.location = data.url
}
});
you have to concatenate the variable. That's all.
redirect('controller_name/function_name/parameter/'.$redirectURL);

AJAX not coming up a success even though its updating the database

My php is updating the table but not refreshing in javascript have tried several different ways of doing this and nothing is working.
PHP
$sql = "UPDATE INTOXDM.ASTP_FORM SET SUPERVISOR_EID = '".$newSuper."' WHERE FORMID = '".$formId."'";
$row = $xdm->fetch($sql);
$return["color"] = $row['APPRENTICE_SIGNATURE'];
$return["json"] = json_encode($return);
echo json_encode($return);
?>
Javascipt
var data = {
"formId": formID,
"newSuper": newSuper
};
data = $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "src/GetInfo.php",
data: data,
success: function() {
location.reload();
}
});
I'd start by modifing the code like this:
var data = {
"formId": formID,
"newSuper": newSuper
};
// No need for serialization here,
// the 'data' parameter of jQuery.ajax accepts JS object
// data = $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "src/GetInfo.php",
data: data,
// As suggested by Rocket Hazmat, try to add an error callback here
error: function(jQueryXHR, textStatus, errorMessage) {
console.log("Something went wrong " + errorMessage);
},
success: function(jsonResponse) {
// Try to reference the location object from document/window
// wd = document or window as seen here http://stackoverflow.com/questions/2624111/preferred-method-to-reload-page-with-javascript
// Also watch out, usually browsers require a user confirmation before reloading if the page contains POST data
// One of these should be fine
wd.location.assign(wd.location.href) : go to the URL
wd.location.replace(wd.location.href) : go to the URL and replace previous page in history
wd.location.reload(<true/false/blank>) : reload page from server/cache/cache
}
});
Also, this might be a shot in the dark but the parameter dataType gave me problems sometime in the past, so if you are sure about the json returned by your php script, you could use the eval function to jsonify the response
$.ajax({
...
// Remove data type
// dataType: "json",
...
success: function(plainTextResponse) {
// Eval response, NOT SAFE! But working
var jsonResponse = eval('('+ plainTextResponse +')');
...
}
});
Your ajax is expecting json data and your php is sending malformed json string. Send a correct json string and your script will work fine.
Your php json_encode should be like this:
$data = json_encode($return);
echo $data;

Json object in javascript Codeigniter

This is the Jquery that calls the function in controller. But it is not able to read the Json_encoded object. I am using codeigniter. Why?
$(this).ajaxSubmit({
type : "POST",
url: '../index.php/user/signin', // target element(s) to be updated with server response
cache : false,
dataType:'json',
success : function(data){
data = $.trim(data);
alert(data);
var obj = jQuery.parseJSON(data);
alert(obj.Condition);
},
error: function(){
}
Controller
$arr = array('Condition' => $condition, 'Message' => $msg);
// header('Content-Type: application/json');
echo json_encode($arr);
Try to use eval instead parseJSON
In js:
$(this).ajaxSubmit({
type : "POST",
url: '../index.php/user/signin', // target element(s) to be updated with server response
cache : false,
dataType:'json',
success : function(data){
data = $.trim(data);
alert(data);
var obj = eval('(' + data+ ')');
alert(obj.Condition);
},
error: function(){
}
I think also that it is not necessary to use $.trim to process response data
Try
url: <?=site_url('user/signin')?>,
If you are not posting anything you can simply use jquery getjson.
http://api.jquery.com/jQuery.getJSON/
It works fine.
check browser console, and tell me any errors are there.

Categories

Resources