I have a page where a user can "view more info", an ID is sent to a php page which then queries the database. It then returns some data, with some of the data I want to put this into a textarea, the other into a standard div.
How can I send multiple responses back, and how do I know what the data is? e.g. send name and address, how do I know what the php page is sending back so that I can interpret the data on client side?
Is there a better way than using
httpxml.responseText.indexOf("something")
As the two responses may contain similar data? What I hope to do is send two variables from the PHP page and then "see" these variables on client side?
Hope I haven't made this too confusing, thanks.
Javascript only please.
Return JSON containing all your values from the PHP. Then after getting the response your javascript can do whatever you'd like to do with the values.
http://www.php.net/manual/en/function.json-encode.php
--PHP--
$responseArr = array('a'=>1, 'b'=>2);
echo json_encode($responseArr);
If I remember correctly (i do this with jQuery now), just performing eval() on your response text will form the object for you.
--javascript-- (just vanilla js right? you didnt mention jQuery or anything)
this is probably inside your onreadystatechange block
var r = xhr.responseText; //assuming you name the XMLHttpRequest object 'xhr'
var rlist = eval('('+r+')');
document.getElementByID("foo").innerHTML = rlist['a']; //or whatever you want to do with these
document.getElementByID("bar").innerHTML = rlist['b'];
Related
I would like to push JavaScript value into php:
var temp = $('#field_id').val().charAt(0);
temp returns values 1-4.
var value = "<?php echo $variable[ ..... ]['id'] ; ?>";
how to insert instead .....
Its impossible, the main reason is that Php is rendered server side ( so before it arrives to the client computer), while JavaScript is rendered in the browser ( so in the client PC).
Depending from your requirement, you may use an ajax request to get the info and update the dom with javascript, or use GET or POST request with the js variable required so that PHP will have it before it renders the page.
If you wold give me more information, I may probably help you, but the question is not specific enough
I want to do the following and do not know how to best approach it:
I have a Facebook like Wall in a Social Website I created.
Every wall Post is a PHP Object with several "comment" objects attached to it.
All Relevant Data is currently fetched from the Database at the time the page loads and works as I wanted it to.
My Wall is getting quite long so I would like to implement infinite scrolling via JQuery and Ajax.
I wanted to send a request for more post objects to a php page which would instantiate them and send the finished objects back. Now I have read that this is bad practice sending PHP Objects via JSON and that it can lead to Problems and potential attack vectors.
How should I approach this? Write the entire wall in Jquery? Have it send Requests for the Data to PHP but display everything with JQuery instead of PHP?
A few pointers would be very appreciated.
You should send AJAX request for needed posts and return ready HTML which you can just append to the container with $('wall_container').append($(new_post_html));
I would say load the initial page and append the data to the wall as you get it. No need to send objects. All the data you need will be in the responseText of the request object
var request = new XMLHttpRequest();
var form = new FormData();
form.append('param_1',val_1);
form.append('param_2',val_2);
request.open("http://example.com/getPostsForWall.php","POST",true);
request.send(form);
request.onreadystatechange = function(){
if(request.status==200 && request.readyState == 4){
//Successful request
response = JSON.parse(request.responseText);
//Want to append a title using jquery to your wall that has an id of wall?
$("#wall").append("<h2 class='wall-post-title'>"+response.post_title+"<h2>");
}
};
This is assuming you have your server side code returning a variable with the key 'post_title' when you send your response
Hi I'm trying to learn PHP and javascript, therefore I tried to do an exercise about passing data but I didn't understand the js function and currently unable to do anything.
Here is the code
php-code.php
$v1=$_GET['v1'];
$v2=$_GET['v2'];
$v3=$_GET['v3'];
//Some operations about them
echo $output;
my-js.js
var v1 = $('#v1 option:selected').val();
var v2 = $('#v2 option:selected').val();
var v3 = $('#v3 option:selected').val();
//This is where I want to pass these variables to my php file and get the output
//But i don't know how
js-execute.php
//this is where my js gets the variables at first
PHP is a server-side language while JavaScript is a client-side one. This means that PHP will be executed when someone requests a page, but the browser will only get the result of the PHP code. On the other hand, JavaScript is sent to the browser and the browser will execute it at the appropriate time (when the page loads or when an event happens). That's why if you look at the source code of a page, you will be able to see the JavaScript code, but never the PHP code.
If you want to pass values from JavaScript to PHP, you will need to make a remote call to a PHP file. PHP isn't like JavaScript – once it's done running its code, it won't be able to respond to anything without a reload of the page.
The easiest way to send something to a PHP file and fetching the result with JavaScript can probably be achieved with JQuery. It has a function $.get which will fetch a given URL. Just be sure to properly validate the input on the server side – never trust user input.
JavaScript (using JQuery to send v1, v2 and v3 to page.php)
function requestPage(v1, v2, v3) {
$.get('page.php', {'v1':v1, 'v2':v2, 'v3':v3}, function(data) {
alert(data);
});
}
PHP (a trivial example)
// Be sure to properly validate input!
if(isset($_GET['v1']) && is_scalar($_GET['v1'])) {
echo strrev($_GET['v1']);
}
Well i wanna create an Ajax Drag and Drop Shopping cart using only javascript and ajax. Currently i'm using the example in this page as a stepping stone. Right now it's only with local jquery and it works fine but i want to make the cart work with ajax calls. Note that i do not want to use a server side language( like php, rubby, asp etc), only html and javascript.
My initial thought was that at the $(".basket").droppable i should add an ajax call to another html page containing the "server logic" in javascript, execute in that file all the necessary steps( like reading the get variables (product name, product id and quantity), set a cookie and then return an ok response back. When the server got the "ok" response it should "reload" the cart div with the updated info stored inside the cookie.
If this was with php i would know how to do it. The problem is that as far as i know, you can execute javascript once it reaches the DOM, but how can you execute that js from inside the page that isbeing called upon ? ( thanks to Amadan for the correction)
I've thought about loading the script using $.getScript( "ajax/test.js", function( data, textStatus, jqxhr ).. but the problem with that is that the url GET variables i want to pass to the "server script" do not exist in that page.
I havent implemented all the functionality yet as i am stuck in how to first achieve javascript execution inside an ajax target page.
Below is a very basic form of my logic so far
// read GET variables
var product = getQueryVariable("product");
var id = getQueryVariable("id");
var quantity= getQueryVariable("quantity");
//To DO
//--- here eill go all the logic regarding cookie handling
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
alert('Query Variable ' + variable + ' not found');
}
Any help regarding this matter will be appreciated.
Note: Logic in simple words:
1)have an html page with products+cart
2)Have an "addtocart.html" with the "Cart Server Logic"( being the target of the ajax call when an item is dropped into the product.)
If you have some other idea on this, please enlighten me :)
thanks in advance
Foot Note-1:
if i try loading the scipt using
$("#response").load("ajax/addtocart.html?"+ $.param({
product: product,
id: id,
quantity:quantity
})
);
i get the alert about not being able to find the url parameters( something that i thing is normal as because the content is being loaded into the initial page, from which the request is started, there are no get parameters in the url in the first place)
The problem is that as far as i know, you cannot execute javascript contained in the target of an ajax call, as that page never reaches the browser interpreter.
This is either incorrect or misleading. The browser will execute any JavaScript that enters DOM. Thus, you can use $.load to load content and execute code at the same time. Alternately, you can use hacked JSONP to both execute code and also provide content as a JSON document.
EDIT: Yes, you can't get to the AJAX parameters from JavaScript. Why do you want to? Do you have a good reason for it, or is it an XY problem?
The way I'd do it is this:
$('#response').load(url, data, function() {
onAddedToCart(product, id, quantity);
});
and wrap your JS code in your HTML into the onAddedToCart function.
Depending on what exactly you're doing, it could be simplified even further, but this should be enough to cover your use case.
I have a page that I have a page I pull from the server every x seconds using some ajax, and then I replace some HTML on the site with the new HTML pulled from the server. The problem has always been that there is a form in that HTML. I want to know is there a way to preserve the value of the form (that the user has entered) when replacing the html in javascript.
Use two callback functions (you should use $.ajax), in the callback before sending (beforeSend(x){ /your code here/; }) you save the parameters (to an array or hashtable): saved = $(element).val(); then in the second callback (use success(x){}) you write them back in. using $(element).val(saved);
var save = document.getElementById('userForm').value;
//replace HTML
document.getElementById('userForm').value = save;
Two ways,
Send and then replace the value in the HTML on the server
Using JavaScript, save it in a session: http://www.webreference.com/authoring/languages/html/HTML5-Client-Side/
I'd say the best solution would be to combine the two and save a session on the server, then load it each time you load the HTML.
-Sunjay03