I have a quite complicated problem:
I use the PHP Simple HTML DOM Parser to fetch some price data from different webshops.
The data is shown on my website. The problem is that I need data from about 10 shops with about each 50 products. So about 500 links all in all.
The Links are retrieved from an CSV.
I want it like this:
Open the csv -> retrieve the link -> parse the price data from the link -> show it on the website
My first try was this:
var file = 'shops.csv';
Papa.parse(file, {
delimiter: ";",
download: true,
header: false,
dynamicTyping: true,
complete: function(results) {
$.each(results.data, function(i, item){
$.ajax({
type: 'POST',
url: "parser.php",
data: {url:item[4]},
success: function(data,status){
if(data){
var output = '' + data +'';
$('table tbody tr[data="'+item[1]+item[3]+'"] td').append(output);
}
},
async:true
});
});
}
});
Now all links are parsed synchronous which crashes the server. When the ajax call is done asynchronous the data is only shown when the last call is done.
The perfect way should be step by step... get the link -> get the price -> show the price -> next.
Related
I found a script on the net, which makes two PHP files interact.
Specifically, the first file (details.php) shows some statistical data of a football match. If the match is in progress, I show the live score by running another PHP file (live_score.php). The two files interact thanks to the following script, present in the details.php file
$(document).ready(function(){
setInterval(function() {
var id=<?php echo"$id"?>;
var x = "<?php echo"$cod"?>";
$("#risultato").load("live_score.php", {var:id, x});
refresh();
}, 5000);
});
from details.php, I call live_score.php passing it some parameters.
These parameters are used by the live_score.php file to retrieve the score and other information in real time.
To print the result on the screen in details.php, I use a simple ECHO inside the live_score.php file, but I would like to retrieve this data and the others in a different way, via ajax if possible, but I don't know if it can be done and how....can you help me please? Thank you
I think you have already solved half of your problem. From your code , you should first remove the "refresh()" to stop reloading the page every 5 seconds.
then make sure that the the payload is correct, because the word "var" is a reserved keyword in JavaScript.
HTML
<div id="risultato"></div>
Javascript
$.ajax({
url: "live_score.php",
type: "POST",
data: { id, x},
success: function(response) {
//this response will be the data from "live_score.php"
//now assuming that
// 1. you use vanilla javascript with plain html + css
// 2. the returning reponse looks like this
// [{"teamName": "theTeam1", "score": 10}, {"teamName": "theTeam2", "score": 10}]
//Clear the current score
$("#risultato").empty();
// Now iterate through the response,
$.each(response, function(index, item) {
var teamName = item.teamName;
var score = item.score;
var html = "<p><strong>" + teamName + "</strong>: " + score + "</p>";
// this code will append (add to the end) the data iterated
$("#risultato").append(html);
});
},
error: function(xhr, status, error) {
//if your code or ajax call had any problems ,
//you can debug here and write error handling logic here, like
if(error){
alert("failed to fetch data");
console.log(error);
}
}
});
I am absolutely new to trirand's jqGrid. I have a fundamental question. I have a form which calls a php file and the latter echoes a JSON response after a submit button. I can format the JSON data in the form needed by jqGrid as mentioned in the manual. But how do I populate it without using another button. I have tried:
$("#output_grid").jqGrid({ //grid5 function starts
url: "searchresults.php",
datatype: "json",
mtype: "GET",
................
................
what I mean is How do I trigger the grid to read the data sent by php file?
function start_post_data(){
$.post(
'script.php',
{ a : 1,
b : 2
},
start_get_data_ajax,
'json'
);
}
function start_post_data_ajax(data, statusText, xhr){
// add the data to the grid
$("#selectieatable").jqGrid("clearGridData", true).trigger("reloadGrid");
i=0;
$.each(data['rows'], function(key, val) {
jQuery("#selectieatable").jqGrid('addRowData',i+1,data['rows'][key]);
i++;
})
}
Try to trigger the reloadGrid event after you've received your search results like this:
$('#output_grid').jqGrid('clearGridData'); // Remove previous data
$('#output_grid').jqGrid({
url: 'searchresults.php',
datatype: 'json',
...
}).trigger('reloadGrid', [{ page: 1 }]); // Reload Grid, and start showing page 1
TL;DR at bottom of post
I am building an application for mobile OS. This is the relevant code:
var pageId;
$(document).ready(function(){
var output = $('#output');
$.ajax({
url: 'http://dev.123456789.co.uk/db.php',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
$.each(data, function(i,item){
var linkedPage = '<h2>'+item.eventName+'</h2>'
+ '<p>Description: '+item.description+'</p><p>Type: '
+ item.type+'</p><p id="pageid">'+item.id+'</p>';
output.append(linkedPage);
pageId = $('#pageid').html();
localStorage.setItem("pageId", pageId);
});
},
error: function(){
output.text('There was an error loading the data.');
}
});
});
Basically, the code goes to a PHP file stored on our dev server and returns data from the database, in this case its eventName, description, type and id, the id being the id of the row in the database (primary key).
In each iteration it outputs the correct item.id at: '+item.id+''.
However, when you go to click each link to take you to the new page localStorage.setItem -> pageId is always the same, so it always equals 1, the first id in the database. However I need it so that when you click the link it takes you to the correct ID for each iteration.
As far as I am aware I cannot do a get/post because the application cannot read PHP because it is for a smartphone, so the data handling on the device is through javascript/data sent from JSON (and structure with HTML); any ideas?
EDIT: displaySinglePost.html:
var pageId;
$(document).ready(function(){
pageId = localStorage.getItem("pageId");
document.write("pageid: " +pageId);
var output = $('#output');
localStorage.clear();
$.ajax({
url: 'http://dev.xxxxxxx.co.uk/single.php',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
$.each(data, function(i,item){
var dataOut = '<h2>'+item.eventName+'</h2>'
+ '<p>Description: '+item.description+'</p><p>Type: '
+ item.type+'</p>';
output.append(dataOut);
});
},
error: function(){
output.text('There was an error loading the data.');
}
});
});
Too Lazy; Didn't Read:
However, when you go to click each link to take you to the new page localStorage.setItem -> pageId is always the same, so it always equals 1, the first id in the database. However I need it so that when you click the link it takes you to the correct ID for each iteration.
As far as I am aware I cannot do a get/post because the application cannot read PHP because it is for a smartphone, so the data handling on the device is through javascript/data sent from JSON (and structure with HTML); any ideas?
Do you mean to set the local storage item "pageID" on every iteration, like on your first example? You may be overwriting the value of it on every iteration(the last iteration would have an item.id of 1).
However, if you want to create a link for each id you should try:
var dataOut = '<h2>'+item.eventName+'</h2>'
+ '<p>Description: '+item.description+'</p><p>Type: '
+ item.type+'</p>';
And have php handle the id via $_GET on page.php
I was wondering if there's a way to allow jQuery loading multiple HTML containers with just one call. For example:
.
<div id='one'></div>
<div id='two'></div>
.
.
<script type="text/javascript">
jQuery("#one").load("somephpmodule.php", "",
function(responseText, textStatus, XMLHttpRequest) {
if(textStatus == 'error') {
jQuery('#one').html('There was an error making the AJAX request');
}});
</script>
.
In the code above, only div "one" will be loaded from the somephpmodule.php output. How to load also div "two" with one call? Or simply do I need to issue multiple calls?
I'd do it like this:
loadUserModules.php handles all of the users modules and returns an array where keys are div IDs (one, two, three etc) and values are the HTML blocks you'll be adding to the page.
This will make one big call to load all your modules.
<script type="text/javascript">
$.getJSON('loadUserModuels.php', function(data) {
$.each(data, function(index, value) {
$("#" + index).html(value);
});
});
</script>
Place both s in one new empty or another tag of your choice with id and load to it.
Personally, I would use the jquery.ajax function to return json with both bits of information, then at clientside, I would get the script to place the appropriate data from the json in to appropriate div tags.
Using this method, you could have many div tags, and a single request would return all the data in json form, which could easily be placed appropriately at clientside.
You don't need to issue multiple calls, you just need to format your request and response differently.
Example, useing json.
$.ajax( {
url: url,
dataType: 'json',
data: data,
success: function( response ) {
$("#one").html( response.one );
$("#two").html( response.two );
}
} );
function loadModules() {
$('#section div[class="module"]').each(function() {
var ajaxModule = $(this);
$.ajax({
url: 'modules/' + $(ajaxModule).attr('modulePage'),
cache: false,
type: 'post',
async:true,
success: function(data){
if(data)
$(ajaxModule).html(data);
else
$(ajaxModule).html('The page that you requested was not found.');
}
});
});
}
You can use a function like this. I wrote it for load modules via ajax. You can set your modules like this;
<div class="module" modulePage="MODULETEST.PHP"></div>
And call this function on;
$(document).ready(function() {...});
It will gonna load all modules.
Btw, don't forget async:true statement on ajax. If not, when you load 3 or more modules at the same time, your page gonna freeze.
Normally async:true statement is default setted but if you assigned async:false on ajaxSetup function like me, you don't have to forget it.
good luck!
i have a set of php function that i want to call on different events mostly onclick with jquery async (ajax).
The first function is called on load
$(document).ready(function()
{
$("#div2").hide('slow');
$("#div1").empty().html('<img src="ajax-loader.gif" />');
$.ajax(
{
type: "POST",
url: "WebFunctions.php",
data: {'func':'1'},
success: function(html)
{
$("#div1").show('slow').html(html)
}
});
The Data: {'func':'1'} --> is a switch statement on the php side
switch($_POST['func'])
{
case '1':
getParents();
break;
case '2':
getChilds(params);
break;
case '3':
getChildObjects(params);
break;
default:
}
"This functions are calls to a soap server" <-- irrelevant.
So when that function finishes i get an array which contains IDs and Names. I echo the names but i want the ID for reference so when i click on the echoed name i can call an other php function with parameter the ID of the name...
How do i get rid of the switch statement?? How do i call properly php functions and pass params to it??? How can i save this IDs so when i click on an item with that id an other php function is called??
Plz feel free to ask any question, any answer is welcome :)
``````````````````````````````EDIT``````````````````````````````````````````
$(document).ready(function()
{
$("#div2").hide('slow');
$("#div1").empty().html('<img src="ajax-loader.gif" />');
$.ajax(
{
type: 'post',
async: true,
url: "Parents.php",
data: {'id' : 12200},
dataType: "json",
cache: false,
success: function(json_data)
{
$("#div1").empty();
$.each(json_data, function(key, value)
{
$("#div1").append('<p class="node"><b>['+key+']</b> => '+value+'</p>');
$(this).data('id', key);
});
}
});
$("p.node").click(function()
{
var id = $(this).data('id');
alert('The ID is: ' + id);
});
});
I got json communication working but my problem is the data stuff,
when i click on a node the id is undefined... it gets printed but when i click on it oupsss.. so the problem is how can i properly attach the ID to each corresponding .. .
You can avoid the switch statement by using an MVC framework that routes your request to the proper function. For example, using CodeIgniter REST Server, you might have the following URL's to your functions:
http://myserver/my_api/parents
http://myserver/my_api/children
http://myserver/my_api/childObjects
You can then POST the parameters along with each AJAX request.
You would probably also want to return the ID you pass as part of the response, so it will be available when you make a request for the next function.
One solution for managing your ID's would be to encode your data as JSON. This will allow you to pass the whole PHP array to Javascript, and have it natively understand and read the ID's and Names.
To encode your PHP array as JSON, try this:
echo json_encode($my_array);
(You'll need PHP 5.2+ for this to work)
This will print out JSON data when the page is requested. Next, in your JavaScript add a "dataType" argument to your Ajax function call. Something like this:
// Get JSON Data and Save
$.ajax({
type: "POST",
url: "WebFunctions.php",
data: {'func':'1'},
dataType: "json",
success: function(json_data) {
$("#div1").data(json_data);
}
});
// Display the ID when clicked
$("#div1").click(function(){
var id = $(this).data('id');
alert('The ID is: ' + id);
});
This tells the Ajax function to expect JSON back.
When the success function is called you can access the "json_data" variable and find all the ID's and Names just as you had them in PHP. You'd then need to write some code to appropriately save those ID's and Names. They can then be used later on (ie. when you click on the button etc).
EDIT: I've updated the code above. The JSON data is now associated with the HTML element "#div1", so you can refer back to it in the future. I've also added a simple click event. Whenever the element is clicked, it's ID will be displayed.