How to retrieve HTML and variables with jQuery/Ajax and PHP - php

I have an HTML form which uses selections from a drop-down list to populate a mySQL table, but with jQuery / AJAX calling an external php file to update the display of entered lines below the original form.
The purpose of the form is an order entry system, and as such works: select an item, see it added to the list. The problem that I have is that as well as having the entered items displayed, I want to show the total order value updating. I thought that I would be able to use a PHP session variable, but that doesn't seem to work unless the original page is refreshed.
Therefore, my question is: is there a way to get session variables (or any other sort of variable) back from my external php file as well as the HTML that I am appending to the displayed page?
If it helps this is the code that I'm using to call the external php when adding a new row:
$.ajax({
type: "POST",
url: "ajaxInsertOrderLine.php",
data: dataString,
cache: false,
success: function(html){
$("#orderItems").append(html);
document.getElementById('inputStockNo').value='';
document.getElementById('qty').value='';
document.getElementById('totalAmount').value="<?php echo $_SESSION["totalValue"]; ?>";
}});
where "ajaxInsertOrderLine.php" is the external file, 'inputStockNo' and 'qty' are two form variables being sent to the script and zeroed after a successful insertion.

You can pass many values back to your jQuery script in the form of an array. For instance, I could pass the following:
session_start(); // necessary for getting/setting SESSION data
print json_encode(array(
"username" => $_SESSION["username"],
"msgCount" => 0,
"userHTML" => "<p>There are no new messages</p>";
));
Then from your jQuery code, you'll use the JSON method of data-retrieval:
$.post("page.php", {}, function(results) {
alert(results.username + " has " + results.msgCount + " messages.");
$("messages").append(results.userHTML);
}, "json");

Why not just scrap the session variable idea - do the total order value calculation on the server in the php page and just send back the value along with item you're adding to the list?

you could return a Json object (maybe using getJSON) containing the two different variables you want to retrieve, one being the html to append and ther other being the total order value.

I found a script here: Javascript Session Variables which does what I want, and may help anybody else who is looking to use session variables with AJAX.

Related

Sending data ajax

I have a page called post-blog.php, in here I've set-up a blog entry. I have all this data being saved into one variable. Its displaying this data in an array.
var data = title + content + image + datetime + categories;
How can I send this data to another page called publish.php and redirect the user to that page ?
I've tried to set up a ajax to do this but its not working. Any suggestions ?
$.ajax({
type: 'POST',
cache: false,
url: 'publish.php',
data: data,
success: function( data ) {
alert ( data );
}
});
return false;
});
As per my understanding of the problem, you need to pass the data to a new page and open that page.
If this is your question then this can be done without AJAX, basically AJAX does not even provide solution here. Instead you can just pass all the data to your new page in query format as below -
var page = 'publish.php?title='+title+ '&content='+content+'&image='+image+ '&datetime='+datetime+'&categories='+categories;
Then just change the window location as below
window.location.href = page;
And to get all those variables in your PHP file, do the following in publish.php on top -
if($_GET['title'])
{
$title = $_GET['title'];
}
// similarly get all the data in publish.php file and continue with your page
I am assuming all your variables are strings. If they are not, for example the datetime may be an object, change them into a string first.
Docs say Object must be Key/Value pairs or a string.
Objects work well for this, try something like:
var data = {title: title, content: content, image: image, datetime: datetime, categories: categories};
If your data is coming from a form check out jQuery's serialize.
I've never tried to pass as a string in a POST, but my gut feeling is it would need to be in a format similar to passing the data through the url.
var data = 'title=' + title + '&content=' + content;
Also keep in mind the data in the success function is not the same as what is being passed to the php page. This is what the php page will return. If you're php page returns nothing your alert will be empty. When I'm testing I like to throw something like echo $_POST['title']; in the php file to see something come back.
Here is a similar question that might help too.

Passing a Php Variable Through Ajax to Update a Frame

I have a server-side PHP page that draws data from an SQL database to populate an array of PHP variables. I use the last array value for each variable to initially populate the data into the 3rd frame of a form (i.e., value = ). This form has a "previous" and "next" link that I want to use to populate the 3rd frame of the form with the "previous" or "next" set of variable values (i.e., value = ) dynamically without loading the entire page. While I'm very familiar with javascript, php and sql this will be the first time I've tried to use AJAX. What I'm trying to do is pass the array number or counter, which is a php variable, to an AJAX function which increases or decreases the array counter (i.e., $counter) so that the values for the next set of variables appears in frame 3 of the form. My problem is that I'm sure that I can pass the current $counter value to the AJAX function which will process it as a javascript variable but how can I then pass the result back to update the php variable in frame 3 of the form? Any help will be very much appreciated.
Blacksquare:
My php web page does the first part. It gathers data from the underlying SQL database and places it into a php array. When the web page initially loads, the most recent or last record is used to populate the form fields that are all in a single frame using something like this (value=$dataField[$counter]). This works when the page is initially loaded populating all of the frame fields with data from the last record in the SQL database. What I'm trying to do is create an AJAX function activated by clicking on the "next" or "previous" link (i.e., an onclick event) that takes the $counter value and increases or decreases it by one (1) and then refreshes the frame displaying fields from the "next" or "previous" php array record in the same frame without reloading the page.
You need to create a php file which will handle the ajax request (passing the variable as post parameter) and echo your response in the php file.
Then in ajax file you will get response in success, update the response using jQuery into the form.
Note: Don't forget to put 'exit' after the response in php file.
For example:
$.post( "test.php", { counter: <?php echo $counter; ?>}).done(function( data ) { alert( "Data Loaded: " + data ); });
What about altering appropriate HTML elements using JavaScript after you get results of the ajax call? There is no need to set the php variable and then to use that field to set a value in HTML when you can alter that HTML value directly from JavaScript.
You can't pass a variable back into a static page generated by php. Probably the best approach is to load only the form on page load. Then grab the dynamic data using an ajax call to another php script on the server side (I'm using jQuery for the ajax).
$.ajax({
type: "GET",
url: someURL, //A link to your php script that will load the data
dataType: "json" //Ask for json data from the server
}).done(function(data) {
nextRecords = data;
getNextRecord();
}).fail(function(resp) {
console.log("Something Went Wrong");
});
Move your sql logic to a separate php script accessed at someURL and have php pass back an array of json data like this
$query = ...Your select query returning an array of results
echo json_encode($query);
exit;
Now when a user hits the next/previous button, you can easily grab the latest record without posting to the server.
function getNextRecord() {
if (nextRecords.length > 0) {
var record = nextRecords.pop();
var node = document.getElementById(node_name);
node.innerHTML = record;
if (currentRecord){
prevRecords.push(currentRecord);
}
currentRecord = record;
}
}
function getPreviousRecord() {
if (prevRecords.length > 0) {
var record = prevRecords.pop();
var node = document.getElementById(node_name);
node.innerHTML = record;
if (currentRecord) {
nextRecords.push(currentRecord);
}
currentRecord = record;
}
}

Best method of passing large array to PHP

I am trying to find the best method for passing a large array of IDs from one page to the next.
I've built a simple downloadable image site that allows users to select any number of images to download. Right now, when a user selects an image its ID is stored in a JSON string inside a cookie. The problem I've been having is finding the best way to pass the JSON to the review before downloading page.
Currently, I'm sending the JSON as a URL parameter but I'm not sure if this is the smartest solution since the number of IDs in the JSON could reach into the hundreds.
I've looked in PHP sessions but I don't really understand how can I enable the user ability to add/subtract from the variable once the page has been loaded.
$(function(){
$('.download_cart').click(function(){
var urlArray = [];
obj = JSON.parse(getCookie("downloads"));
if(obj != null){
if(obj.items.length !== 0){
$.each( obj.items, function( i, value ) {
urlArray.push(obj.items[i].id);
});
}
}
window.location = cart_url+'?array='+urlArray;
})
});
Try POSTing your data to the new PHP page:
var data = 'urlArray='+urlArray
$.ajax({
type: "POST",
url: 'new_php_page.php',
data: data
});
Now you'll be able to get your variable at $_POST['urlArray'] on your new page.
http://api.jquery.com/jQuery.post/
Consider to pass them in a set of ajax-requests, by 200 (for example, to not overflow input limit) IDs in each request.
Assign urlArray to a hidden field then submit the form, it can parse large no of array to another page

Two Forms In PHP

I have one php file that displays two forms. THe first Form displays data of customers from a table in mysql which also includes a checkbox. The second form contains data from another table and also includes a checkbox this form contains messages. I need to send messages selected with the checkbox to the list of customers selected in the first form.
Can I do that with pure php? or will I need to use javascript? please point me to a tutorial.
you need download Jquery library...and read what is ajax
get value
var value = $("#customer").val();
we get value for selector where id="customer"
get cheked
if($('#customer').is(":checked")) { } else { }
send data on server
var value = $("#customer").val();
$.ajax({
type: "POST",
url: "default.php",
data: "name="+value,
success: function(data){
alert('ok!') ;
}
});
we send data on server post method...we send variable value, value = value in value id="customer"
Good luck! Sorry for my English :)
The initial problem with what you are trying to accomplish is that you cannot natively submit two forms concurrently.
Is it absolutely necessary to have two separate forms? If so, you will need to implement something like this (written by Roatin Marth) in order to copy values over from one form to another when submitting:
function form2form(formA, formB) {
$(':input[name]', formA).each(function() {
$('[name=' + $(this).attr('name') +']', formB).val($(this).val())
})
}
Of course, if your business requirements do not require two separate forms, you can just place all the values into a single form and then process it with PHP. If you require validation of the form prior to submission, you will want to do that with Javascript first.
Once in PHP, you will get the values from the $_POST superglobal. You can then do what you need to do with it.
// With each customer checked, send checked messages
foreach($_POST['customers'] as $customer)
{
// With this customer, send all messages
foreach($_POST['messages'] as $message)
{
// Send $message here
}
}

display html select (from PHP) via jquery?

So I have a PHP backend that pulls some data from SQL, let's just say its a list of user ID numbers.
I want to be able to display that list in an html select, via jquery, after a button click.
In an attempt to partially answer my own question, I assume that I could either have a jquery function perform an ajax request, grab the data from PHP/SQL, and then somehow spit out the select with jquery. Or, I could perhaps do the SQL query via PHP right there on the page, and somehow have the jquery function grab the output from that and put it into a select.
How would you do it?
a fill-in-the-blanks code example follows:
idea 1:
function button_click() {
$.ajax({
url: "PHP_backend.php", // this does the sql query and returns the results
type: 'POST',
data: 'returnquery',
success: function(result) {
//????? put the result array or whatever into a submit, perhaps with a foreach or something similar..??
}
}); // end ajax
}
Or idea 2:
$result = mysql_query("SELECT userIDnumbers FROM users",$db);
while ($row = mysql_fetch_array($result)){
/// throw these results into an array or similar, $userIDarray[]
/// maybe I could have this PHP create hidden html fields for each row, and insert its value, and then get that via jquery
}
function button_click() {
/// create the html select, displaying the values from the sql query
/// get values from hidden html fields?
}
if you are sure that the button will be clicked always or very most of time, idea2 is better becouse overhead of send/receive Ajax (trafic) and its delay (time) will be removed
if the web page is "public" (not for an intranet, behind a vpn), I strongly advise to not use any sql in jquery. It's simplistic to call the php ajax response file with arbitrary sql (ie what I want), and even modify anything in the data or database.

Categories