Send complex sets of data to php from javascript without ajax - php

How can javascript pass data, for example from an HTML table, without using AJAX?
I am lacking the understanding of how to actually pull data, format (into json likely), and pass it.
I am trying to pass data to a php function that sends a file to the user to download. (something ajax can't handle as I understand it)
EDIT - please give an example of posting of some rather complex data.
EDIT2 - an exmample...
I populate a table via an ajax response Object. What would be a good way to get this data I am formatting into a form that I can send to a php file via a form?
function getSalesByDeviceComplete(responseObj)
{
var cashTotal = parseInt(responseObj.data[0].cash_total).toFixed(2);
var creditTotal = parseInt(responseObj.data[0].credit_total).toFixed(2);
var grandTotal = (parseInt(responseObj.data[0].cash_total) + parseInt(responseObj.data[0].credit_total)).toFixed(2);
htmlStr += '<ul>';
htmlStr += ' <li>';
htmlStr += ' <table class="ui-widget ui-widget-content contentTable">';
htmlStr += ' <thead>';
htmlStr += ' <tr class="ui-helper-reset ui-widget-header">';
htmlStr += ' <th class="contentTableKey">Payment Device</th>';
htmlStr += ' <th class="contentTableValue">Sales</th>';
htmlStr += ' </tr>';
htmlStr += ' </thead>';
htmlStr += ' <tbody>';
htmlStr += ' <tr>';
htmlStr += ' <td class="contentTableKey">Credit Card</td>';
htmlStr += ' <td class="contentTableValue">$'+creditTotal+'</td>';
htmlStr += ' </tr>';
htmlStr += ' <tr>';
htmlStr += ' <td class="contentTableKey">Cash</td>';
htmlStr += ' <td class="contentTableValue">$'+cashTotal+'</td>';
htmlStr += ' </tr>';
htmlStr += ' </tbody>';
htmlStr += ' <tfoot>';
htmlStr += ' <tr>';
htmlStr += ' <td></td>';
htmlStr += ' <td id="salesTotal" class="contentTableValue">$'+grandTotal+'</td>';
htmlStr += ' </tr>';
htmlStr += ' </tfoot>';
htmlStr += ' </table>';
htmlStr += ' </li>';
htmlStr += '</ul>';
$("#contentData").html(htmlStr);
}
The response object looks something like...
<response_GetSalesByDevice>
<data>
<cash_total>0.00</cash_total>
<credit_total>0.00</credit_total>
</data>
<success>1</success>
</response_GetSalesByDevice>
Alas, there are several response objects that are much more complex than this.

By posting form data to a PHP script via the browser, rather than using an asynchronous HTTP request.

The way it "used" to be done (which is of course still very current):
http://www.w3schools.com/html/html_forms.asp

If by "Without AJAX" you mean without using XMLHttpRequest, then the most common way is to fill a hidden field in a form.
Javascript can change a hidden field, then when the user submits the form as usual, the hidden value is passed through as well.
This can be used for things like gathering stats on screen size etc, which are non-critical and can be passed through when Javascript is enabled, or not when it isn't.

You seem to have some crossed understanding of what AJAX and JSON are/do or most likely I do not understand what you mean from your question.
If you do not want to use ajax you will have to use the normal submit just like the two people above me suggested.
However, if you are sending a relatively small amount of data you might be able to send a GET request to your PHP script with ajax, which will then respond with a file. Something like:
http://yourserver.com/test.php?getVariable=29472938472
Test.php script looks at the get variable and returns the associated file.
Entirely possible with AJAX.
Please tell me if I've gone down the wrong path.

You could post via a form in the usual way.
The form, however, is targeted at a hidden iframe. This way you stay on the current page and the file that the server returns is handled in the usual browser way.

Instead of calling the data directly, you should call a php file that contains:
/myphpfilethatgetsstuff.php
http://mydatadomain.com/?q=getmesomexmlplease";
$json = file_get_contents($jsonurl,0,null,null);
$json_output = json_decode($json);
echo "<pre>";
print_r($json_output);
echo "</pre>";
?>
Then iterate over the data creating both the file and the html output.
In the main file use this javascript:
$('div#results').load("http://mydomain.com/myphpfilethatgetsstuff.php");
with this div somewhere:
<div id="results"></div>
and this link:
Your File

One alternative to XMLHttpRequest objects is making asynchronous calls via an iFrame imbedded in the page. This is a documented "AJAX" design pattern when xmlhttprequests cannot be used.
There are some components for jquery (ie, AJAX Upload) that utilize this method.
Documentation and sample here:
http://ajaxpatterns.org/IFrame_Call

Related

getJSON within getJSON

I have had a search but not finding anything that is helping me solve my little issue. It would be nice if I was throwing some kind of error but the following code executes partially perfectly.
In essense, I have a list of train departure at a station (returned in JSON format by a custom API departures.php), but as I am looping through this returned array, I want to call a second custom API which brings up details of the service (based on a variable pulled from the first API which is the unique identifier) using service.php.
Here is an example of the service unique ID
Y5G8DkxFcxw7+xmbbBNM1g==
However the second getJSON returns nothing at all.. its as though it doesn't exist.. though the php API functionality perfectly if used on its own
Here is the code, any pointers greatly appreciated. PLease note I have stripped out a lot of the HTML that generates the view from departure.php returned data and just left the bare basics in.
NOTE : this is purely an experiment, and not a commercial product.
var $crs = GetURLParameter('crs');
$.getJSON('departures.php?crs='+$crs, function (data) {
var headertemplate = '<div class="col-md-6"><h2>Departure from ' + data.GetStationBoardResult.locationName + '</h2></div>';
var date = new Date(data.GetStationBoardResult.generatedAt);
var dateString = date.getFullYear() + '-' + ("0" + (date.getMonth() + 1)).substr(-2) + '-' + ("0" + date.getDate()).substr(-2);
var timeString = ("0" + date.getHours()).substr(-2) + ':' + ("0" + date.getMinutes()).substr(-2);
headertemplate += '<div class="col-md-6 text-right"><h2>Last updated: ' + timeString + ' </h2></div>';
$("#headerArea").html(headertemplate);
var template = '<table class="table">';
template += '<tbody>';
for (var i in data.GetStationBoardResult.trainServices.service) {
template += '<tr>';
template += '<td colspan="4">Calling at ';
$service = data.GetStationBoardResult.trainServices.service[i].serviceID;
$.getJSON('servicedetails.php?service='+$service, function (data2) {
for (var j in data2.GetServiceDetailsResult.subsequentCallingPoints.callingPointList.callingPoint) {
template += data2.GetServiceDetailsResult.subsequentCallingPoints.callingPointList.callingPoint[j].locationName;
template += ', ';
}
});
template += '</tr>';
}
template += '</tbody>';
template += '</table>';
$("#dataArea").html(template);
});
Just to follow this through, the URL sends a three letter string which is used to pull off the station departure which is an array.
The script generates the station information and returns into the div with id header.
The script then loops through all the departures, building up the template which it then injects into the div with id dataArea.
In each departure, the script pulls off the details of each service to list where the train will be calling at - THIS is the bit that is totally ignored.

MySQL database update through AJAX and PHP

I have been going to stackoverflow for hints and tips in my programming journey but I have yet to register. . .till now.
My question is, is it possible to update/edit mysql data which I've inserted into an html/css table without having to go to another page?
for example:
when looking at the table in my browser, I wanted to edit my email information. I could just simply press the edit button then the email field becomes a text field right on the same page then I could just update it and hit save?
thanks!
EDIT(added my code):
$(button#edit).on('click', function() {
// get email inline to this edit button
var email = $(this).parent().siblings('td.email').html();
// change button from edit to save
$(this).attr('id', 'save-email').html('Save');
// change email display to input field
$(this).parent().siblings('td.email').html('<input type="text" id="user-email" value="'+email+'" />');
});
and this is the table I used which is formatted with php which also grabs data from my database:
echo ' <tr>';
echo ' <td>' . $row['name']. '</td>';
echo ' <td>' . $row['age']. '</td>';
echo ' <td>' . $row['sex']. '</td>';
echo ' <td>' . $row['email']. '</td>';
echo ' <td>' . $row['contact_no']. '</td>';
echo ' <td>' . $row['school_name']. '</td>';
echo ' <td>
<button id = "edit">EDIT</button>';
nothing happens,your help is greatly appreciated!
Yes, it is possible. Here are a few hints:
Use jQuery to listen to a click-event on the button and insert the text-field.
On Submit, use jQuery to send an ajax-request to a different php-file (like save.php).
Inside this file, you can do any mysql-queries you would normally do.
Again through jQuery, display the result of the queries to the user.
Yes. It's possible. Make a hidden div tag in your html code.
By means of ajax when you press button that div tag will be filled up by textbox / text.
Go through some tutorials related to ajax.
Sharing you an idea on how it works
JS script:
$('button#update').click(function(){
$.ajax({
url : 'yourpagehere',
data : {
id : '1' // send sample data to url
},
type: json,
sucess: function(response){
//Your script
});
});
});
PHP:
function yourpagehere(){
$id = $_POST['id']
$result = updateUserInfo($id); //Your script updating info in your database
json_encode($result); //Your response
}
Then you use firebug and check the console log on what you're ajax returned.
Yes, It is possible using AJAX.
AJAX is very powerful jQuery tool which is used to make asynchronous javascript calls which means you can submit data to another page without page loading.
As well as you can fetch data and fill dynamically in your page using AJAX without reload/load page.
You can find many tutorial and examples of AJAX.

Process dynamically created web form with JQuery and PHP

I've been wrestling with a problem that I just cannot seem to solve. I've got a web form that is built from a MySQL query that's run from PHP and returned to JQuery that displays a gallery of movies that the user can give a numeric rating. I'm wanting to send the form back to PHP for processing and writing to the database.
function loadGallery()
{
$('content').append('<form id="movieRatings" action="../php/saveRatings.php" method="post">).html();
$.get('../php/getMovies.php')
.done(function(data) {
var query = $.parseJSON(data);
for (var i = 0, len = query.length; i < len; i++) {
var galleryMovies = '<div class="movContainer">' +
'<div class="movie">' +
'<a title="' + query[i].mov_title + '" href="../' + query[i].mov_title + '.html">' +
'<h3>' + query[i].mov_title + '</h3>' +
'<img src="../imgs/' + query[i].poster_path + '" /></a>' +
'<input type="number" name="' + query[i].mov_title + '" >' +
'</div>' +
'</div>';
$('#content').append(galleryMovies).html();
}
$('#content').append('<input type="submit" value="Submit"></form>');
})
.fail(function() {
$('#content').html("Epic Fail!") ;
});
}
The form displays without any issues, but clicking the submit button doesn't even send the request for the "saveRatings" PHP file. I'm sure I'm missing something simple, I just can't seem to figure out what that is. My first thought was that it was because the gallery isn't part of the actual html, but from what I've read that shouldn't have anything to do with it.
And pointers/sugestions/insight would be appreciated.
instead of
$('#ID').click(function(){
// do something here
});
switch to
$(document).on("click", "#ID", function(){
// do smth here
});
Your first assumption was true, if the element is not part of the initial html, then any events bound to it won't work unless you go with my second approach. You can find more about this behavior in the jquery documentation.
L.E: same goes for the submit action, in case i was not clear with the click example:
$(document).on("submit", 'form#formID',function(){
// do smth here...
});

JSON array to an HTML table and display the data inside td tag

I have json array return as bellow
{"id":16,"minutes":146}
{"id":17,"minutes":137}
{"id":18,"minutes":123}
{"id":22,"minutes":84}
I'm trying to render above json array inside table tbody td which json array id's equal to td id's and display the minutes inside td tag
for example json id :16 minute:146 and display it in <td id="16">146</td>
<table>
<thead>
<tr>
<th>op</th>
<th>Minutes</th>
</tr>
</thead>
<tbody>
<tr>
<td>op1</td>
<td id="16">0</td>
</tr>
<tr>
<td>op2</td>
<td id="17">0</td>
</tr>
<tr>
<td>op3</td>
<td id="18">0</td>
</tr>
<!--....and goes on -->
</tbody>
</table>
js
$.ajax({ url: statUrl, type: 'POST',
data: {
begin: begin,
end: end
},
success: function(data){
}
});
Your JSON is invalid it should only represent one object, a valid version of what you have will be
[{"id":16,"minutes":146},
{"id":17,"minutes":137},
{"id":18,"minutes":123},
{"id":22,"minutes":84}]
If your data IDs directly correspond to already existing DOM element IDs then it should be rather easy:
for (var i = 0; i < data.length; i++) {
$('#' + data[i].id).text(data[i].minutes);
}
This is using jQuery ofc.
you can use json_decode($json, true) in php to convert the json to an array then loop over it's elements and build your table.
If you want to do it client side, I think you must create table, tr and td elements manually and populate them. ExtJS has ready grid for this.
Server side is easier.
I created a jsFiddle here: http://jsfiddle.net/5pKjW/11/
As Musa stated, the JSON you posted is not valid, it should be an array containing all the objects.
The code following is basically what you need to do inside the success callback, just use data instead of result.
What I do is creating a table, appending a row for every element of the array and then appending the whole table to an element of the DOM.
var result = [{"id":16,"minutes":146},{"id":17,"minutes":137},{"id":18,"minutes":123},{"id":22,"minutes":84}];
var $table = $('<table><thead><tr><th>op</th><th>Minutes</th></tr></thead>'),
$tbody = $('<tbody>').appendTo($table),
i;
for (i = 0; i < result.length; i++){
$tbody.append('<tr><td>op' + (i+1) + '</td><td id="' + result[i].id + '">0</td></tr>');
}
$table.appendTo('#container');
As T.J. Crowder commented, a valid HTML4 id attribute can't start with a digit. If I were you, I would prefix it with a string (<td id="prefix' + result[i].id + '">0</td>).
MrOBrian suggested to use a rendering engine. Maybe for a simple case like this, and if you don't need a rendering engine elsewhere, it's an overkill, but that's absolutely something worth considering, if you need something more complicated in the future.
as suggested fixed json array to
{
"25":72.3833,
"17":116.3167,
"16":25.75,
"34":28.3333,
"29":136.8831,
"19":40.9166,
"32":43.6,
"22":83.9001
}
and js
$.getJSON(statUrl, {begin: begin, end: end}, function(data) {
$.each(data, function(key, val) {
$('#op_' + key).text(Math.ceil(val));//also fixed td id
});
});
so got the result as expected.
thanks for your time.

embed PHP in jQuery .append()

Is this possible? I know the code below looks a whole heap of mess but i want to make it more messy by embedding PHP into it. On each click i'm appending a row onto a table, but i need to include a dynamic dropdown into one of these <td>'s by pulling results from a mysql db. Where it says this: <td><p class="add_edit">Add/Edit</p><input type="text" class="project_ref_input" name="project_ref_input" /><p class="project_ref"></p></td>
Instead of p tags i'm going to have a PHP built dropdown...how can i achieve this?
$('#items').append('<tr class="tableRow">
<td><a class="removeItem" href="#"><img src="/admin/images/delete.png"></img></a></td>
<td class="supp_short_code">' + supp_short_code_db + '</td>
<td class="om_part_no">' + omPartNo + '</td>
<td>' + supPartNo + '</td><td>' + cat + '</td>
<td class="description">' + desc + '</td>
<td>' + manuf + '</td>
<td>' + list + '</td>
<td>' + disc + '</td>
<td><p class="add_edit">Add/Edit</p><input type="text" class="quantity_input" name="quantity_input" /></td>
<td class="price_each_nett price">' + priceEach + '</td>
<td class="cost_of_items"></td>
<td><p class="add_edit">Add/Edit</p><input type="text" class="project_ref_input" name="project_ref_input" /><p class="project_ref"></p></td>
<td class="cost_total_td"></td>
</tr>');
Because Jquery is client side - you cant append PHP like you suggest.
You would have to write a PHP script that is triggered by a callback from Jquery, the PHP script would recieve some parameters, and return the HTML that would be needed to achieve your solution.
Does this help?
step 1: add row
// Your code
//just call another function to get db driven combo.
get_education_combo();
step 2: write following javascript function for retriving the result from php code and sending to html element.
function get_education_combo()
{
var url ="print_education_list";
//alert(url);
var contents = AjaxRequest(url);
//alert(contents);
//return contents;
//send the result to html
document.getElementById("elementID").innerHTML=contents;
}
function AjaxRequest(url)
{
//alert(url);
if(xmlhttp != null){
if(xmlhttp.abort)
xmlhttp.abort();
xmlhttp = null;
};
if(window.XMLHttpRequest) // good browsers
xmlhttp=new XMLHttpRequest();
else if(window.ActiveXObject) // IE
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
if(xmlhttp == null)
return null;
xmlhttp.open("GET",url,false);
xmlhttp.send(null);
// alert(xmlhttp.status);
if(xmlhttp.status >= 200 && xmlhttp.status < 300)// 2xx is good enough
return xmlhttp.responseText;
else
return null;
}
step 3: php code
print_education_list()
{
$education="your query";
echo '<select name="edu_name" id="edu_name" style="width:70px;">';
foreach($education as $edu)
{
echo '<option>';
echo $edu->sEducationName;
echo '</option>';
}
echo '</select>';
}
That's It. BEST OF LUCK. I have prepared this combination during development of DeskTop application by php.
You would generate the dropdown on the server, then fetch the dropdown using the jQuery $.ajax method. Alternatively you could return a JSON array of option/values and build your dropdown using something like $.each to iterate the array.
If you are thinking about having the PHP in the javascript then sending that back to the server to be executed then DON'T. That's a WTF of the highest order. You didn't mean that right? (You might want to change the title of your question - becasue that's what it looks like).
edit: For all you guys saying client side PHP is impossible. Check this out!
http://thedailywtf.com/Articles/Client-side_PHP.aspx
PHP is server-side only, so you can't embed it into the JS that you send to the client's browser and expect it to run. In order to achieve your result, you'll either need to use PHP to render the list in the initial page, or use an AJAX call to pull the list from a service URI.
If you are generating this code dynamically on the server, i.e. you want to add the mysql results to the HTML markup before sending it to the client, you would do something like this:
<td><?php $VARIABLE_TO_ADD ?></td>
This is assuming you know how to pull the data out of the DB and create a variable with that data. PHP looks for the <?php ?> tags within an HTML document and parses whatever is between them.

Categories