capture rawurldecode into variable php - javascript

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?

Related

Ajax doesn't get to success function. Always error function. It fails to post data to another file

Please be patient. This is my first post as far as I remember.
This is a part of my calendar.js script. I'm trying to POST data that I fetch from modal window in index.php to sql.php.
function saveModal() { /*JQuery*/
var current_date_range = $(".modal-select#daterange").val();
var current_room_number = $("#mod-current-room-number").val();
var current_room_state = $("#mod-current-room-state").val();
var myData = {"post_date_range": current_date_range, "post_room_number": current_room_number, "post_room_state": current_room_state};
var myJSON = JSON.stringify(myData);
$.ajax({
type: "POST",
url: "sql.php",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
data: myJSON,
beforeSend: function() {
$("#ajax").html("<div class='loading'><img src='/images/loader.gif' alt='Loading...' /></div>");
},
success: function(result){
$("#ajax").empty();
$("#ajax").html(result);
$("#ajax").fadeIn("slow");
window.location.reload(true);
},
error: function(){
alert(myJSON);
$("#ajax").html("<p class='error'> <strong>Oops!</strong> Try that again in a few moments.</p>");
}
})
}
I get the data just fine (as you can see I have checked in the error: function() with alert(myJSON);). It looks like this: {"post_date_range":"12/19/2018 - 12/28/2018","post_room_number":"118","post_room_state":"3"}. Nevermind that the daterangepicker.js returns dates in the hideous MM/DD/YYYY format, which I would very much like to change to YYYY-MM-DD. The real problem is, the code never gets to success: function().
Now my sql.php is in the same folder as calendar.js and index.php.
In sql.php I try to retrieve those values with:
$currentDateRange = $_REQUEST['post_date_range'];
$currentRoomNumber = intval($_REQUEST['post_room_number']);
$currentRoomState = intval($_REQUEST['post_room_state']);
I have checked many other SO Q&As and none have helped me solve my problem. I don't see any spelling errors. It's not disobeying same origin policy rule. I don't want to use jQuery $.post function. Anyone sees the obvious solution?
You want to send array in post rather than the string so directly send myData to get array value in your PHP file rather converting to JSON string It would work with your current PHP file as you require.
You should specify a POST key for the JSON data string you are sending:
var myJSON = JSON.stringify(myData);
(...)
$.ajax({
(...)
data: 'data=' + myJSON,
You need to parse (decode) this string in your PHP file to be able to use it as an array/object again:
$data = json_decode($_REQUEST['data']);
$currentDateRange = $data['post_date_range'];
$currentRoomNumber = intval($data['post_room_number']);
$currentRoomState = intval($data['post_room_state']);
Also, dataType in jQuery.ajax function is specified as "The type of data that you're expecting back from the server." according to jQuery documentation. As far as I can tell from your code, you might rather expect something else as your response, so try excluding this line.
I am sorry to have burdened you all. It's my third week programming so my lack of knowledge is at fault.
I did not know how dataflow works between AJAX and PHP in the URL...
While I was searching for other errors, I printed or echoed out many different things. The PHP file should echo only 1 thing, although it can be an array with multiple values.
Like this for example:
$return_arr = array("sql"=>$sql1, "result"=>$result, "out"=>$out);
echo json_encode($return_arr);
I appologize again.

Encode ajax request data sent to a php page and then decode

I have a https request using ajax to external php page like in the code bweloow. Please note there are some strange non UTF-8 chars that have to be encoded, otherwise i would get a strange return.
//ajax request to external site
sometext = "I only wear Rtrtrr® shoes, and my name is Åron";
sometext = some_encoding(sometext); //a PSEUDO code line
$.ajax({
type: "POST",
url: "http://targetsite.com/process_text.php",
data: sometext,
cache: false,
success: function(proc_text) {
alert()
}
});
On php page, then, I need to decode and use some_decoding(sometext) instead of some_encoding(sometext).
Is there any way to encode such text, with some_encoding function i javascript that has analog function for some decoding in php.
For example encodeURIComponent doesn't convert all the chars, while Base64 I used is not the same in PHP and Javascript in some cases. Is there something that is the same.

script doesn't load after ajax response

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

Trying to get data from a php page that fetch a json data using jquery

Hi I'm trying to get the data I fetch using PHP.
the page is named twitter-fetch.php
now what I know is, that page is now filled with json data converted to associative array because I json_decode() on the the data. (please correct me if I'm wrong).
now what I'm trying to do is calling that page using ajax.
the name of the project is phone. the my js file is in the js folder. and the twitter-fetch.php is in php folder. I just want to see the result in console for now, help... frowning
I'm still new to ajax and json so I'm really not sure on what I'm doing here
$(document).ready(function(){
$.ajax({
url: '/phone/php/twitter-fetch.php',
type:'POST',
contentType: 'application/json',
dataType: 'json',
success: function(result){
console.log(result);
alert('success!');
}
});
});
this the php line where I used the json_decode and stored it in $string
$url = "https://api.twitter.com/1.1/search/tweets.json";
$requestMethod = "GET";
$getfield = '?q=%23forsale&result_type=recent&count=100';
//the TwitterAPIExchange is a PHP Wrapper that I used
$twitter = new TwitterAPIExchange($settings);
$string = json_decode($twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest(),$assoc = TRUE);
UPDATE:----- $.getJson
$.getJSON('./php/twitter-fetch.php',function(result){
var output = $.map(result, function(item, index){
var listitem = $('<li></li>');
$('<h2>'+item.user.name+'</h2>').appendTo(listitem);
return listitem;
console.log(listitem);
});
$('#js-result-list').html(output);
});
Right now, you're sending a request to the link [website directory]/phone/php/twitter-fetch.php which probably isn't a real file. Instead, you need to go back to the phone/ directory using ../ and then put php/twitter-fetch.php:
$(document).ready(function(){
$.ajax({
url: '../php/twitter-fetch.php',
type:'POST',
contentType: 'application/json',
dataType: 'json',
success: function(result){
console.log(result);
alert('success!');
}
});
});
Also, remember when you put / at the beginning of a relative link, that relative link gets appended to the website directory. If you want it to be appended to the lowest directory the current file is in, don't put / at the beginning.

submitting a form using $.ajax

I'm calling this function when the dom is ready on $().submit
but it seems not working there is no response from server
$(function(){
$("#logingform").submit(function(){
var values =$(this).serialize();
call_server("../php/login.php",values);
});
});
function call_server(URL,DATA)
{
$.ajax(
{
type:'POST',
url : URL,
data : DATA,
dataType:'json',
success:function(response){
$("#d1").append(response);
}
}
);
}
nothing seems to get back from the server.
server code
<?php
$email = $_POST['loginemail'];
$password =$_POST['loginpassword'];
echo json_encode(array('returned_val' => 'yoho'));
There is an extra semi colon following your ajax option:
data : $(this).serialize();,
vs correct
data : $(this).serialize(),
You do not need to parse the json that is returned, since you already have dataType:'json' defined in the ajax options.
$("#d1").append($.parseJSON(response));
That is not necessary.
If you want to show the response object as a string, then you need to stringify it instead:
$("#d1").append(JSON.stringify(response));
Also, you have a syntax error on this line:
data : $(this).serialize();,
Remove the ;.
Your data for a POST should be in json format, so rather than $(this).serialize(), use $(this).serializeArray() for your data. This will pass those values for POST body rather than in the querystring.

Categories

Resources