AJAX to retrieve and store object in a variable - javascript

I have two files. One is index.php where the user clicks and invokes an AJAX request. The second one is process.php whic sends back data back to index.php.
function AjaxResponse() {
var myData = 'connect=1';
jQuery.ajax({
type: "POST",
url: "process_facebook.php",
dataType: "text",
data: myData,
success: function(response){
$result = response;
window.location.replace("http://myurl.com");
}
the $result doesn't here. I can do like this $('#something').html(response); but can't store the value returned in a variable.

Kind of hard to tell what you would like here. But I'm going to guess that you want to store the result of the ajax call into a variable in php. So I'll remind you the order in which things proceed for a server/client web interaction.
Server processing ==> client side processing ==> repeat.
The only real way to store that value in a variable after receiving the data from your ajax request would be to submit a form and have your data serialized into JSON or xml and then parse it.
Alternatively, your process_facebook.php file could insert your data into a database and you could return a key to your callback, and either create a cookie on the users browser of that key, or have the browser pass that key as a get variable to your index.php (sanitize it so that a malicious user can't just go entering whatever they want), and then do what you want with that information.
To clarify, the session is not stored on the browser, it is stored on the server, you cannot set any session variables on the browser unless you did it in an ajax call to the server.

Related

Passing JavaScript values to PHP file using XHR call

I have a PHP file on a server that needs to take dynamic values from client-side use on a web page in order to query my database. The user will click a link which (as well as directing the user to a new tab) takes the document location string that the link is connected to. I am currently trying to pass these values to the server side code using jQuery/AJAX and an XHR call, but when I run it, it seems that the PHP does not execute properly. Here is the JavaScript code:
// Clicking the link
$('a.docs').on('click', function(){
// Getting the values needed for the query from existing table
var theData = subtable.row($(this).parents('tr')).data();
// The document string
var thedoc = theData[7];
// Pass the document value to the PHP file on the server
$.post('https://example.com/TEST/dashboard/change.php', {
document: thedoc
});
// Make XHR call to execute the PHP file on the server
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://example.com/TEST/dashboard/change.php", true);
xhr.send();
});
As you can see, I try to send the value of thedoc to the file on the server before making the GET XHR call. Here is the what PHP code on the server does:
<?php
// The line that grabs the document variable being passed
$document = $_POST['document'];
// ... MySQL query stuff using $document as parameter...
?>
When I test this and click the link on the webpage, the JavaScript correctly grabs the document link variable, it's just the passing that has not been working. Any ideas on what I am doing incorrectly?
I cannot comment :(
I agree with jorgonor1.
You are performing 2 separate requests to your server.
The first. You are sending data to the server with JQUERY in the section $.POST(...). And from the sample code, ignore the results.
Then secondly, you perform a clean request of the generic page with the xhr request.
If you use $.POST(), and want to perform something with the result from the server try:
$.post('https://example.com/TEST/dashboard/change.php', {document: thedoc}, function(result){
//do something with the data returned form the server, server response stored in "result" variable
});
See the example on W3Schools
if you want to use jQuery, just try
let data = form.serialize();
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
or if you want to use xhr, you need to send the data as key/value pair string:
let data = "document=thedoc"

Passing multiple arguments through HTTP GET

I have an HTML file referencing a PHP script to perform various functions. One of the ways the HTML file calls the PHP script is through an HTTP GET. The GET request should pass three parameters and return a list of all saved events as a JSON-encoded response.
So far, I have the following but I'm not sure how to pass the three arguments through the HTTP GET. Also, I'm not sure if I am returning the JSON-encoded response correctly:
if($_SERVER['REQUEST_METHOD'] == 'GET'){
echo json_encode(events.json); }
GET requests are done through the URL... So if you want to pass three GET requests you would do...
http://www.domain.com/target.php?param1=whatever&param2=whatever&param3=whatever
target.php represents the PHP script file you want to send the information to. You can have as many variables as you want but just keep in mind that every other GET request has to be separated by an & symbol. The first param simply has to be started off with a ? symbol.
If you want to use Javascript, I would recommend using JQuery. You can do something like this
$.get('target.php?param1='+whatever+'&param2='+whatever2, function(data) {
alert(data);
});
Or you can use window.location to send a link with the appropriate link above.
If you want to use AJAX specifically, here is a way of doing it with JQuery (there are ways with Javascript that I could update later if necessary:
$.ajax({
type: "GET",
url: "http://www.domain.com/target.php",
data: { param1 : "whatever", param2 : "whatever", param3 : "whatever" },
success: function(result){
//do something with result
}
})
If you want to access the variables, you can call $_GET['param1'] or $_REQUEST['param1'] to get access to them in PHP. Simply change the name in the brackets to the desired variable you want and store it in a variable.
If you want to access the params with Javascript... well the most efficient way is to go and decode the URL that was used and pull them out. See here
Hope this helps!
You can access the parameters from the URL via the $_GET superglobal in PHP.
For example, if your URL is http://example.com/test.php?param1=foo&param2=bar, then you could access them in PHP like so:
$param1 = $_GET['param1'];
$param2 = $_GET['param2'];
See http://www.php.net/manual/en/reserved.variables.get.php for more details.
As for returning a valid JSON response, you can check out this answer. It uses PHP's header function.

Execute ajax only one time

I want only execute my ajax post 1 time, i try to avoid to the user refresh the page and execute so much times the ajax post,
I thought in create a cookies, but i don't know, and i'm no sure, somebody know how?
This is my jquery.
var t = jQuery.noConflict();
t( document ).ready(function() {
t.cookie("example", "foo", { expires: 7 }); // Sample 2
console.log( "ready!" );
alert(t.cookie("example"));
var data = '<?php echo json_encode($json_full);?>';
t.ajax({
url: 'my api url',
type: 'POST',
success: function(r) { alert(JSON.stringify(r)) },
dataType: 'JSON',
data: { data: data, }
})
});
/I need run this AJAX only one time because is a checkout page to send the order, and if i refresh the page, send every time the same order, and this i don't want/
Thanks a lot!
Things like these can not be safely controlled on the client's browser. Any user with minimal knowledge in JavaScript will be able to open up the developers tools for their browser and manipulate the code or any values you might have stored (such as deleting the cookie you have set).
This limitation should be implemented on the server.
It really depends on the scope of your application. You might be able to limit the requests per IP address, but that might prevent multiple people from the same office for example loading the page at the same time.
Using user authentication and persistent server storage you'll be able to limit the effect of the request, but you probably won't be able to prevent the actual request from being sent as anyone can make that request even from outside the browser. You could store the user_id of the user that initiated the request and only allow the resulting action to occur if a certain time has passed since the last request.
A better solution to avoid double submits, is to use a POST query for the submit request and let the server respond with a redirect to a normal (harmless) receipt/thankyou page.
Then if the user refreshes the receipt page they will simply repeat the GET request to the receipt page and not the post.
You should still add some checks server side to avoid multiple POST requests somehow (using sessions, timestamps or something), in case a malicious user deliberately tries to resubmit.
This will only work on IE8 and above, but you can use localStorage:
var t = jQuery.noConflict();
t( document ).ready(function() {
t.cookie("example", "foo", { expires: 7 }); // Sample 2
console.log( "ready!" );
alert(t.cookie("example"));
if(localStorage['submitted'] === undefined){
var data = '<?php echo json_encode($json_full);?>';
t.ajax({
url: 'my api url',
type: 'POST',
success: function(r) {
localStorage['submitted'] = true;
alert(JSON.stringify(r));
},
dataType: 'JSON',
data: { data: data, }
})
}
});
This way the first time it will run the AJAX because you haven't set the localStorage variable, but upon success you do and it will not resubmit on page refresh.
If you wanted to have the ability to send again upon a future visit, just use sessionStorage instead of localStorage. Same syntax and everything.

jquery, ajax, json data chunking

I need to return a large amount of json data via an ajax call. Is there a built in jquery or javascript function to handle "chunking" of the data
ie: I need to be able to handle the data as it is returned by keeping the ajax call open and receiving chunks of data as it is sent from the server.
One method might be a self referencing ajax polling function something like...
(function getData() { setTimeout(function() {
$.ajax({
url: "locationofserver",
success: function(data){
// handle data returned (append chunks?)
// get next bit
getData();
},
dataType: "json"});
}, 20000);
})();
Where the first call returns information about the data length and how many chunks are available. This of course means the server needs to manage the breaking up of the data into chunks...
I would ask why you would need to chunk it though instead of just ensuring a persistent ajax connection until done? If you are truly looking to handle a data stream then maybe http://signalr.net/ or other push technology?

how to send asynchronous request to php page using jquery ajax

i am new to web development creating a kind of social networking website for college project. I want to include update the messages count in the message menu every time there is a new msg in the database for the user(like facebook message menu on homepage)
But it's frustrating learning ajax, however after searching on web and reading some topics from some books I came to the solution that i can make an $ajax call in my js file in the homepage and send data ('name'=>'user') stored in javascript cookie that i have created on loading of home page after the user login, to a php file which will search across the recent_msg table in database to fetch the recent message for the logged in user if any after fetching the php file will create the html file with code snippet and further another jquery code will append that snippet from file to the message list menu.
the PHP part is not the problem but how can i send the username to the php file using jquery ajax api, here is the code what i think i can apply but i am doubtful in that if this is the correct way
$(document).ready(function{
setInterval ( function()
{
var usr = getCookie("name");
$.ajax ( {
url: '/phpScripts/recent_msg.php',
type: 'POST',
data: usr,
success: function(data){
}
} );
},10);
});
what is the purpose of success function in the code?
data needs to be in the form of an object / key-value-pair (EDIT: or if a string, as a valid querystring). data: { name: usr }. However, since it's in a cookie, your PHP page will have direct access to that cookie. It's safer to let your session cookie tel the PHP page who the user is instead of relying on an AJAX call to tell the PHP page who it is.
http://php.net/manual/en/features.cookies.php
So I'd drop data from your AJAX call altogether, and in your PHP page, use $_COOKIE["name:"]
Then whatever HTML gets passed back from the PHP page will arrive in the data call. If it's HTML, then simply add it to your HTML to some message div, such as.
<div id="recent-messages"></div>
<script type="text/javascript">
$(document).ready(function{
setInterval ( function()
{
var usr = getCookie("name");
$.ajax ( {
url: '/phpScripts/recent_msg.php',
type: 'POST',
data: usr,
success: function(data){
$('#recent-messages').html(data);
}
} );
},10);
});
</script>
The success function executes whenever your ajax call completes successfully. This means that the page actually exists and no server-side errors occurred on the page. The variable data will contain whatever information is returned from the page on the sever /phpScripts/recent_msg.php. Generally this is either json or xml, but it entirely depends on your implementation of recent_msg.php.
If the user has to log in that means you have to have created a session. In that case you can store the logged in user's information such as their name in $_SESSION on the server and there is no need to store it as a cookie. Since $_SESSION is already on the server, there is no need to send that data via ajax in any case.

Categories

Resources