I've been using stackoverflow for months now as it really is the the most reliable resource I can think about. However, I now have my own question.
I'm working on a script that displays available courses in an HTML5 page using ajax after calling some php/MySQL interaction. I was using jQuery 1.4.1 (yeah... i know) and due to some interesting new plugins available, I updated to 1.10.2.
Now my page doesn't display the product of the PHP/SQL processing anymore, nor does the autoscroll work.
I did some search and didn't find any answer.
I was hoping you guys would see directly the incompatibility in my code, or the usage of a too old syntax.
Trigger :
<a class="internal-link" href="#" onclick="goToByScroll('reanimation');"></a>
Script :
function goToByScroll(id){
$.ajax({
type: "POST",
url: "kernel/appel-tableaux-ajax.php",
dataType: "script",
data:{type_cours : id},
success: function(array){
var objet = JSON.parse(array);
var message = objet["message"];
var nombre = objet["nombre"];
$("#conteneur-tableaux").html(message);
$("#nombre-cours").html(nombre);
if(nombre==0)
{
$("#titre-section-tableaux").css("color","darkred");
}else{
$("#titre-section-tableaux").css("color","darkgreen");
}
$('html,body').animate({scrollTop: $("#section-tableaux").offset().top},'slow');
}
});
}
PHP code (I erased stuff where mistakes are less probable) :
ob_start(); // I want to catch all the 'echos' to insert them in an array.
while ($donnees = $reponse->fetch())
{
// Lots of Date comparison stuff and many ECHOS.
}
$out = utf8_encode(ob_get_contents()); // --- I put every echos inside the 'OUT' variable.
ob_end_clean();
// --- I want to send back 2 things to my script, some infos about the courses available, and the total number of available courses. So I create an array.
$output_final = array ("message" => $out, "nombre" => $compteur_cours);
echo json_encode($output_final);
?>
As you can see, I'm a beginner in Ajax and jQuery usage.
UPDATE :
Thanks a lot to all those who already helped.
I tried the debug tools in Chrome, the php generates exactly what it's supposed to do, which means that my ajax is able to call the PHP code placed in kernel/appel-tableau-ajax.php. The Console.log() placed in the success case doesn't display anything.
I'm adding a screenshot of the syntax errors that Chrome detected. If someone could help me to understand how to handle those errors it would be wonderful.
Link to the screenshot
Also, Safari's debugger says : SyntaxError: JSON Parse error: Unexpected identifier "object".
I can't believe all this worked on the old jQuery version...
Thanks a lot, I hope I'm not asking too much!
if your php code return json why the 'dataType' in your ajax is 'script'? try change it to json.
hope it will work! :)
Related
I need advice on my ajax progress bar while executing a long PHP script treating pictures.
I know there are plenty of questions on stackoverflow already like
Show progress for long running PHP script
or JQuery ajax progress via xhr
or update progress bar using ajax request seconds)
Most of the examples I see are using the file size to calculate the progress.
But in my case I would like to calculate percentage based on images_treated / total_images.
So I still can't make this work as I want.
In JS bellow I commented the not working progress function I took from another question and dataType: 'json' for tests but I would prefer if I can still use a JSON return.
Questions
The console.log() will only log once - when the full script is done. Am I doing it wrong?
What should I write to replace the comment?
in some answers, the PHP headers are set to header('Content-Type: application/octet-stream'); is it mandatory or just nicer?
Javascript:
$.ajax(
{
type: 'GET',
// dataType: 'json',
url: formAction,
data: 'addImagesToArticle',
cache: false,
xhr: function()
{
var xhr = new window.XMLHttpRequest();
// Download progress.
xhr.addEventListener("progress", function(e)
{
console.log(e);
// I saw this piece of code from another question it is supposed to work... Maybe my PHP?
/*var lines = e.currentTarget.response.split("\n");
var progress = lines.length ? lines[lines.length-1] : 0;
$('#progress').text(progress);*/
}, false);
return xhr;
}
});
My PHP is quite big so I just explain quickly: in the loop on pics I have variables $images_treated and $total_images. After the loop, a summary is returned to JS via JSON in an object like {error: bool, message: string, ...} so if there is a way to make the progress work without echoing but setting a JSON variable that would be perfect!
Thank you for your help!
[EDIT] to add context details.
I want to use this in an admin side, in an article edition with a WYSIWYG, I have dropzone taking care of my multiple images uploads.
then I see the preview of images while each image is put in temp folder on server. I can then remove some images if needed and once all images are definitive, i click a button that will process them for resizing 2 sizes and inject figure tags with img in the article WYSIWYG editor.
Waw I found a solution!
I am happy to discover that new thing I did not know about PHP and share with people who also don't know (in step 3 bellow)!
#riccardo was right talking about socket - which I don't know so well - but I did not need to go that far.
So I had multiple things to solve in my case before being able to get closer of my goal.
not using xhr.addEventListener("progress"... but a second ajax call in a timer: it will also be lighter-weight in resource consumption.
rather than using a timer like setInterval or setTimeout - as requests are async it may come in unwanted order - use a recursive call in callback of first call like:
function trackProgress()
{
$.getJSON('create-a-new-page.html', 'ajaxTrackProgress=1', function(response)
{
var progress = response.progress;
$('#progress').text(progress);
if (progress < 100) trackProgress();
});
}
then realize that my second script call is delayed by first script still running? yes. So the key here is session_write_close()!
I could dig in this way thanks to this good post:
https://stackoverflow.com/a/1430921/2012407
and I posted a very simple example here to reply to another question: https://stackoverflow.com/a/38334673/2012407
Thank you for all your help in comments guys, it led me to this solution. ;)
I'm learning and experimenting with jquery/ajax as I develop a website. I have a page that updates a database. I would like a 'sequence' of responses to display on the screen when the user submits their data (I've seen this done on many other sites).
For instance... user submits form and the page displays:
Received Input
Checking Database - recond number xy
Updating Database
Retrieving Information
etc etc
This is just an example but you get the idea.
I have an ajax call that is initiated on 'click' of the submit button (getFormData just serialises all the form data for me and works fine):
var toSend = getFormData($upgrade_db_form);
var formMessageBox = $("#displayResults");
$.ajax({
url: ajaxurl,
data: {
action: "database_action",
formData : toSend
},
type: 'POST',
dataType: 'TEXT',
beforeSend: function() {
//$form.fadeOut('slow');
formMessageBox.html("starting it up");
},
success: function (data) {
formMessageBox.empty();
formMessageBox.html(data);
error: function (xhr) {
// formMessageBox.html("Oops error!");
}
});
I have a function which gets called by ajax:
function upgrade_database_function() {
echo "testing ";
for($i = 0; $i < 99; $i++) {
echo "percent complete ".$i."%";
}
echo "done ";
die(); // this is required to return a proper result
}
I'm using Wordpress and all the ajax side of things works fine, it passes the form data correctly etc, it's just that I get one long output as though it's cache'ing all the echo's up instead of outputting them in sequence.
I've gone through the jquery ajax documentation and couldn't find how to make it behave the way I want it to. I can live with it the way it is but I think it would look a lot better if I could get it working the way I would like.
Can this be done this way or do I need lots of sequential ajax calls to make it work?
I don't know PHP, but i'm guessing that the echo is just writing to the response buffer... so when all the echos are done the whole response will be returned and you would get the effect that you are seeing... You would need to go with a polling system or something along those lines to get the latest status' from the server and display them I would think... Maybe there is some system in PHP that allows this, but as I said, I don't know PHP.
An Example of Long Polling can be found in this article.
http://www.abrandao.com/2013/05/11/php-http-long-poll-server-push/
WARNING: You may have to do some manual managing of locking of the session in PHP so that your long running call doesn't lock your polling ajax calls: See here:
http://konrness.com/php5/how-to-prevent-blocking-php-requests/
Note that you would likely be wanting to:
create one ajax call that starts the execution of some coded that will take a while... you could put messages that have been generated into a session variable for example in a list of some sort. You would need to lock/unlock the session as mentioned to prevent suspension of AJAX polling calls.
you would create a polling method like in the article that might check the session every 500ms or something to see whether there are any more messages, lock the session, remove those messages and return those messages to the client side and display them.
WARNING: Again, I'm not a PHP person, I may have done this once in my life in PHP (can't remember exactly) but I may be wrong and this may not work, from what I've seen though it looks like it is achievable. Hope this gets you on your way!
Ok guys I know this question has been asked before but I am very new to PHP and JavaScript and hadn't even heard of ajax until i started looking for an answer to this question so do not understand previous answers.
I am creating a site that essentially is a bunch of videos in a SQL database, it shows one video at a time, I would like to have a next and previous video buttons.
However I cant get past this ajax thing so my question is even simpler. I have looked at this question/answer and think it pretty much sums up what im asking:
How do I run PHP code when a user clicks on a link?
I have copied that exact code,
<script type="text/javascript">
function doSomething() {
$.get("backend.php");
return false;
}
</script>
Click Me!
And in my backend.php file i have literally just got <?php echo "Hello" ?> just to test it and therefore my understanding is that when i click the link the javascript onClick event is trigged which in turn calls the backend.php file, which says to print "Hello" to the page. However when i click the link it does nothing.
Eventually obviously im going to need to get a lot more complex with my php functions and calling variables and all that stuff but i like to figure things out for myself for the most part so i learn. However im stuck on this bit. Also whilst im here i will ask another thing, I want to 'give back' to the users of the site for answering my questions but I can only really well enough in HTML and CSS to answer other peoples questions, any advice on being able to find the simpler questions on here so i can answer some.
Thanks in advance :)
It does nothing becuase you don't do anything with the result. My guess is that in the example you took, it does some work and doesn't show anything to the user. So if you just had some stuff you wanted to run on the server without returning any output to the user, you could simply do that, and it would work.
Example from jQuery's .get() documentation
What you do:
Example: Request the test.php page, but ignore the return results.
$.get("test.php");
What you want to do:
Example: Alert out the results from requesting test.php (HTML or XML, depending on what was returned).
$.get("test.php", function(data){
alert("Data Loaded: " + data);
});
Take a look at the .get() documentation. You're using it incorrectly.
You should be passing data (optional) and handling the data that gets returned, at a minimum:
$.get("backend.php",
{
// data passed to backend.php goes here in
//
// name: value
//
// format. OR you can leave it blank.
}, function(data) {
// data is the return value of backend.php
// process data here
}
);
If you pass data, you can retrieve it on backend.php using $_GET. In this case:
$_GET['name'];
$.get("test.php", { name: "John", time: "2pm" }, function(data) {
alert("Data Loaded: " + data);
});
http://api.jquery.com/jQuery.get/
This would alert the data. right now that function only returns false.
$.get('backend.php', function(data) {
alert(data);
});
Your code will not print to the page the way you have it set up; you're part of the way there, in that you have called the page, but the response needs to be handled somehow. If you open up the developer tools in Chrome, you can click on the Network tab and see the request and response to verify that what you coded is actually working, but now you need to put the response somewhere.
By passing a function as the second variable into $.get, you can make your request show up on the page. Try something like this:
$.get("backend.php", function (data) { $('body').append(data); } );
Your code is not handling with that data. So instead, you should use following code :
$.get("backend.php", function(response) {
alert(response);
})
Or, to show that data on UI, assign it to any html element.
For more understanding , please visit :jQuery.get() link
I have an odd problem regarding jQuery dataType.
I have a very simple PHP program that returns (echo's) an XML file (string). Looks like this:
$xmlFile = "sampleXMLFile.xml";
$xml = simplexml_load_file($xmlFile);
echo $xml->saveXML();
My client/javascript code calls the php program via ajax:
$(document).ready(function()
{
$.ajax({
type: "GET",
url: "myPHPFile.php",
dataType: "xml",
success: myCompleteFunction,
complete: mySuccessFunction,
failure: function(data) {
alert("Problem getting XML");
} });
});
The "myCompleteFunction" takes the XML and simply writes the first node into a div element, like this:
function myCompleteFunction(xml)
{
$(xml).find("Row").each(function()
{
$("#result3").append($(this).attr("myrow"));
});
}
OK - in IE 8, this works fine. In Firefox and Chrome I get no results. However, if I change the dataType to "html" I get correct results in Firefox and Chrome and then get no results in IE.'
Continue to go crazy with this. Do I actually need to put conditional logic for the browsers?
The dataType: option explained in the jQuery manual seems clear enough. I even tried to leave dataType out
(per manual: If none is specified, jQuery will try to infer it based on the MIME
type of the response)
I also tried multiple types - e.g. "text xml". No good.
Anyone ever run into this problem? Any direction would be appreciated.
Thank you.
p.s. I know I can read an XML file in jQuery. The resultant XML from the PHP program would be substantially more involved. I only used that as an example.
Updated:
Well, I saw Phil's comment about producing something before XML data sent. There was certainly nothing obvious. I removed a blank line above my first <?php line. This has somehow worked! Still seems odd to me. So my new, tighter PHP code is now:
<?php
// Load XML
$xmlFile = "sample.xml";
$xml = simplexml_load_file($xmlFile);
header('Content-type: text/xml');
echo $xml->saveXML();
?>
I will also pay mind to your other suggestion about properly handling jQuery.ajax() callbacks. Thanks.
I very much appreciate your help w/this!!
Stick with the "xml" dataType and add this to your PHP file before the echo...
header('Content-type: text/xml');
Also, you seem to be mixing up some of the jQuery.ajax() callbacks.
Use success to handle the returned data.
Use error(jqXHR, textStatus, errorThrown) (not failure) to handle HTTP errors
Use complete to execute some tasks after success and error callbacks have executed
ok, i guess I need help ! I searched with every keyword I could think off, but I still cant figure out, please help. Am more of a php guy, and I've just started with jQuery.
Basically, what I am trying to do is to send a jQuery post from a click function. And based on whatever is returned by my php function, show/hide 2 divs. My php function returns a "json_encode" array with 2 simple values, like such :
//==================PHP code ==================================
$message_for_user = "blah blah";
$calculatedValue = 1230;
$responseVar = array(
'message'=>$message_for_user,
'calculatedValue'=>$calculatedValue
);
echo (json_encode($responseVar));
//==================PHP code End ==================================
My javascript code is supposed to accept the values returned by php :
//==================Javascript code ==================================
$("div.calculator_result").click(function()
{
$.post('myCalculator.php' ,{qid:itemID},function(response)
{
$("div.calculation_value").show(500).html(response['calculatedValue']);
$("div#message_for_user").show(500).html(response['message']);
}
}
//==================Javascript code End ==================================
Unfortunately, on the javascript side of my project, the divs are not updated with the values returned by my php functions .... where am I wrong? I hope I was clear in my question, if not, do let me know, and I shall provide any extra info required.
Another thing is that earlier, I was echo'ing only a single value, that is the calculated value (echo $calculatedValue), and everything worked fine, its only after I shifted to echo'in the json encode array that things dont work
var json = $.parseJSON(response); alert(json.message);
Try setting the dataType option:
$.post('myCalculator.php' ,{qid:itemID},function(response)
{
$("div.calculation_value").show(500).html(response['calculatedValue']);
$("div#message_for_user").show(500).html(response['message']);
}, 'json');
NB I have also added the closing brackets ) where you have missed them.
You must parse the JSON response. jQuery has this built-in functionality (thankfully, because otherwise IE6 and 7 don't natively support JSON). Set a variable equal to this:
$.parseJSON(response)
And then, if you're not familiar with JSON format, check the response headers (using Firebug or similar,) and that will help you pick which keys' values you want. If you're looping, I would look into for in statements once the response has been parsed.
EDIT: Using $.getJSON, the parsing is done automatically. Write less, do more. :)
All you gotta do, its tell the Ajax call that you're receiving data type "json". In other words...
$.ajax({
url: "external_file",
method:"post",
dataType: "json", // **************** Note dataType****************
success:function(response){
console.log(response)
// Response will be a javascript array, instead of a string.
},
error: function(){
alert('something went wrong.')
}
})