I'm new to Javascript. The code for a jQuery-ajax-php-cooperation does strange things. It works - sometimes.
This is what I want to do:
- make some settings in a form (works)
- read JSON-file after pressing submit-button (works)
- loop the JSON-items, extract the values of each item and form a parameter-string (problem is here: loop is not (always) executed in the button-pressed-function)
- send parameter-string built from each items values to PHP-file (works if loop is entered)
- receive the response from the PHP-file (html-tag) (works)
- update a form element with the response value (not yet implemented, actually show an alert with the PHP-response for debugging purposes)
The JSON file is valid (tested). The HTML-Page is valid HTML5 (tested). The PHP-script works and returns a valid HTML-Image-Tag (tested).
When I press the button, no responses from the PHP-file are displayed in the alert I implemented for debugging purposes. But this works:
- reload page
- open Firebug
- set breakpoint at loop-begin
- skip one statement forward
- reload page
- the loop is entered, all works fine
I can close Firebug and the loop is performed properly.
The javascript code
<script type="text/javascript">
$(document).ready(function () {
//click event of submit button
$('#generator').click(function(){
// GET variables
var datafile = "my.json";
var logo = false;
// if checkbox is checked
if( $('#logo').attr('checked')){
logo = true;
};
// read data from json file
$.getJSON(datafile,function(data){
//iterate through the data-sets
for(var i=0; i < data.length; i++) {
// get the response from server for each data-set
$.ajax({
type: 'POST',
async: false,
cache:false,
url: 'myfile.php',
data: 'param1='+data[i].field1+'¶m2='+data[i].field2+'&logo='+logo,
success: function(response){
//$('#imgdisplay').html(response);
// alert only for debugging purposes
alert(response);}
}); // end of ajax-call
}; // end of for-loop
} ); // end of getJSON
}); // end of button.click
}); // end of document.ready
</script>
(sorry for bad intented formatting)
I use a for-loop, could not get an each()-loop to work properly.
And this is the form:
<form name="settings">
<label>Source file</label>
<select id="datasource" name="datasource">
<option value="extract">Extract</option>
<option value="filter">Filter</option>
</select><br />
<label>Logo</label>
<input type="checkbox" id="logo" name="logo" value="ON"/><br />
<p> </p>
<input type="submit" value="Start Generator" id="generator" name="generator" />
</form>
<div id="imgdisplay" class="imgdisplay"></div>
What causes this strange behavior? How can I solve it?
$.getJSON()
call. I'm curious whatdata
holds. – Michael Berkowski Oct 29 '12 at 17:05