jQuery json loop with ajax call for php function - php

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+'&param2='+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?

Try to return false from the anonymous click method
$('#generator').click(function(){
....
return false;
}
This will ensure that the click will not post your form

Related

Interaction between client and server using ajax and json response

I have a website, that I am building that allows consumers to order food. The user will search by their Postal code (UK) such as A1 1AA for example. Once they search by their postal code, the restaurants that deliver to their area will appear.
I am currently working on the checkout page, and i want to stop users from inputting a postal code that, that said restaurant does not deliver too. I would like to do this the moment the user presses enter on the postal code field.
I just have no idea how to do this, i have put together some ajax following a number of posts (see below,very first time using ajax so please forgive me if its sloppy) to do this,i know it is not complete but i have no idea where to go from here.
I have a string url with the users area and postal code, within it. and i also have a database with the postal codes the restaurants delivers to, i would like to do something along the lines of if the restaurant does not deliver to the postal code entered echo "Sorry, This restaurant does not deliver to A1. ".
I have tried to achieve this using both AJAX and Jquery
Code
<div id="container">
<form id="myform" name='myForm'>
<input type="text" id='doorno' name="doorno" value="" placeholder="e.g. 2a" min="1" >
<input type="text" id='addlin1' name="addlin1" value="" placeholder="e.g. Brunel Hall">
<input type="text" id='addlin2' name="addlin2" value="" ><br>
<input type="text" id='city' name="city" value="" >
<input type="text" id='postal' name="postal" value="" placeholder=""><br>
</form>
<div id='ajaxDiv' style="background-color:red">Your result will display here</div>
$(function() {
$("#container").keypress(function (e) {
if (e.which == 13) {
e.preventDefault(); // this prevents the default action of a enter
$.post('ajax-example.php',$("#myform").serialize() , function(response) {
$('#ajaxDiv').html(response); // this will echo any response from ajax file
});
}
});
});
I have just tried it in Jquery. It work almost perfectly apart from it doesn't work on keypress but onclick, but i don't know how i would do something along the lines of if $_POST['postal'] is not equal to $postcode( users postcode variable from string url)/ the postcodes the restaurant delivers to column in my db
$(function(){
$('input[name="postal"]').click(function(){
alert('Hello...!');
});
$('#city').keypress(function (e) {
var key = e.which;
if(key == 13) // the enter key code
{
$('input[name = postal]').click();
return false;
}
});
});
As far as I understand, here you are trying to add a keypress handler on the input field.
This handler will make a post request and will validate whether deliver is possible in the specified postal code.
If that's the case then it would be better to use blur handler instead of keypress.
Because keypress will trigger server request for every key pressed, i.e. if user enters 5 digit postal code e.g. AA110 then 5 times post request will be sent which is unnecessary.
For jQuery; You may want to try this approach and see if it does what you want:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
<script type="text/javascript">
(function($) {
$(document).ready(function(){
$(document).keypress(function(e) {
if(e.which == 13) {
if($(":focus").get(0) == $('input[name = postal]').get(0) ){
// DO WHATEVER YOU WANT TO DO HERE
// BECAUSE ENTER WAS PRESSED INSIDE OF THE FIELD WITH THE NAME postal
// FOR TESTING... ALERT SOMETHING...
alert("Sure, you pressed the Enter Key inside of the Postal Field...");
}
}
});
});
})(jQuery);
</script>
You can test and Fiddle it out here: https://jsfiddle.net/csqsLmxh/
OK, so here's how it all ties together.
JAVASCRIPT: JQUERY
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
<script type="text/javascript">
(function($) {
$(document).ready(function(){
$(document).keypress(function(e) {
if(e.which == 13) {
if($(":focus").get(0) == $('input[name = postal]').get(0) ){
// SEND OUT AN AJAX REQUEST TO THE PHP-SCRIPT ON THE SERVER
// HERE WE ARE SIMPLY SAYING:
// ONCE THE USER FINISHES TYPING INSIDE THE POSTAL FIELD & HITS ENTER
// GO TO THE SERVER AND ASK THE SCRIPT: ajax.processor.php TO USE THE
// POSTED POSTAL CODE & CITY TO SEARCH FOR THE NEAREST AVAILABLE RESTAURANT...
// IN THIS CASE WE USE JSON, JUST IN CASE WE MAY WANT TO SEND BACK A COLLECTION OF DATA...
// AND SO OUR AJAX GOES LIKE THIS:
$.ajax({
url: "./ajax-processor.php",
dataType: "json", //<== CHANGE TO "HTML" IF YOU ARE EXPECTING HTML DATA.
cache: false,
type: "POST",
data: ({
postal : $("#postal").val(),
city : $("#city").val()
}),
success: function (data, textStatus, jqXHR) {
// IF OUR AJAX CALL SUCCEEDS AND THUS RETURNS SOME RESULTS
// IN THIS CASE JSON, WE CAN USE IT TO UPDATE THE #ajaxDiv...
// HOWEVER IF WE ARE EXPECTING JUST HTML WE WILL GO A DIFFERENT ROUTE IN THE SUCCESS HANDLER...
// PLEASE, NOTE THAT YOU MAY NOT HAVE BOTH JSON & HTML SIMULTANEOUSLY
// THIS IS AN "EITHER-OR" CASE HERE:
// SO IF YOU EXPECT HTML, YOU ARE ADVISED TO
// EITHER DELETE OR COMMENT-OUT FROM THE BEGINNING
// TO THE END OF JSON HANDLING LOGIC BELOW & VICE-VERSA
if(data){
// ##BEGINNING OF JSON HANDLING...## //
if(data.restaurant){
var output = "<em>Restaurant: </em><strong>" + data.restaurant + "</strong>";
output += "<br /><em>Take-Away: </em><strong>" + data.takeAway + "</strong>";
$("#ajaxDiv").html(output );
}
// ## END OF JSON HANDLING... ## //
// ##BEGINNING OF HTML HANDLING...## //
$("#ajaxDiv").html(data); <== JUST UPDATE THE DIV WITH THE RAW DATA FROM THE RESPONSE... IT IS EITHER HTML OR STRING OR NUMERIC DATA...
// ##END OF HTML HANDLING...## //
}
},
error: function (jqXHR, textStatus, errorThrown) {
console.log('The following error occured: ' + textStatus, errorThrown);
},
complete: function (jqXHR, textStatus) {
}
});
}
}
});
});
})(jQuery);
</script>
HTML
<html>
<body>
<div id="container">
<form id="myform" name='myForm'>
<input type="text" id='doorno' name="doorno" value="" placeholder="e.g. 2a" min="1" >
<input type="text" id='addlin1' name="addlin1" value="" placeholder="e.g. Brunel Hall">
<input type="text" id='addlin2' name="addlin2" value="" ><br>
<input type="text" id='city' name="city" value="" >
<input type="text" id='postal' name="postal" value="" placeholder=""><br>
</form>
<div id='ajaxDiv' style="background-color:red">Your result will display here</div>
</body>
</html>
PHP
<?php
// FILENAME: ajax-processors.php <== MUST MATCH THE URL WE DECLARED IN THE AJAX DEFINITION (JS)
$postal = isset($_POST['postal']) ? htmlspecialchars(trim($_POST['postal'])) : null;
$city = isset($_POST['city']) ? htmlspecialchars(trim($_POST['city'])) : null;
// RUN YOUR QUERIES AND DO ALL YOUR MAGIC USING THE POSTED $postal & $city
// TO DETERMINE WHICH DATA ARE RELEVANT TO BE RETURNED...
// ASSUMING IN THE END YOUR QUERIES RETURNED SAY 2 RESULTS LIKE Derby Inn, Kings Pizza.
// YOU CAN THEN BUNDLE THE RESULTS INTO AN ARRAY (IF IT IS NOT ALREADY AN ARRAY OR OBJECT) LIKE SO:
$arrResponse = array(
"restaurant" => "Derby Inn",
"takeAway" => "Kings Pizza",
);
// HOWEVER, THIS IS NOT NECESSARY IF YOU ARE SENDING BACK ONLY A STRING VALUE...
// IN THE CASE OF A STRING VALUE (SAY, JUST "Kings Pizza")
// YOU COULD JUST DO IT OTHERWISE. LIKE THIS:
/* die("Kings Pizza"); */
// IF YOU DID IT LIKE THIS, BE SURE TO CHANGE YOUR THE "dataType" ATTRIBUTE
// IN YOUR AJAX FROM *JSON* TO **HTML** AND ALSO TO HANDLE THE SUCCESS
// CALLBACK DIFFERENTLY... ***SEE THE JAVASCRIPT SECTION FOR COMMENTS***
// NOW WE ARE DONE... ALL WE NEED DO IS SEND THIS RESPONSE BACK TO THE SCRIPT AS JSON LIKE SO:
die( json_encode($arrResponse));
// ALTHOUGH THERE ARE NO REAL QUERIES HERE OR ANY PROCESSING LOGIC,
// THIS SCRIPT WILL STILL RUN & SEND BACK JSON DATA TO THE JAVASCRIPT
// DOUBT IT? THEN TRY IT....
After talking to you what I understood is that you have successfully done
On pressing enter you sent a query to database
Then from database you sent process it and send error message if postal codes do not match
Now you want to know .howt to process no delivery error message sent from database inside the post callback function so as to provide alert or notification to user
For that purpose I have put down a small example
create two files Example.php and Example.html in root directory and copy each of the files content from here to inside them now in browser type
localhost/Example.htmlpress enter notice each time you run the file the output changes.
Data from php to html page is sent using json format which will be useful to you in future a lot.First data to be sent is inserted into an associative array
then it is encode into json format using json_encode() function in server side
JSON.parse() method is used to parse the json format data obtained here the value of json object is accessed using jsonobjectname.keyName to get the value sent from server.
Here in case
var returned = JSON.parse(data)
console.log(returned.Key);
these lines explains it
And by the way when associative array is converted into json format it looks like this
$result = array("Key"=>"1");
echo json_encode($result);
{"Key":"1"}
Here is document of json_encode function
Another thing I used random variable generator function rand() to simulate both true and false conditions for the loop .
Example.php
<?php
$trueorfalse = rand(0, 1);
if($trueorfalse){//your condition if there is delivery
$result = array("Key"=>"1");
echo json_encode($result);
}else{//your condition if there is no delivery
$result = array("Key"=>"0");
echo json_encode($result);
}
?>
Example.html
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$.post("/NTD.php",function(data){
console.log(data);
var returned = JSON.parse(data)
console.log(returned.Key);
if(returned.Key==0){
$("#NotifcationDiv").html("There is no shipping to your region");
alert(returned["Key"]+"No delivery");
}
})
});
</script>
</head>
<body>
<p id="NotifcationDiv"></p>
</body>
</html>
Disclaimer:Sorry for being late I saw the OP question and worded a simple example of json and php interaction from server to client and I only so the another answer posted down later only

AJAX\JQUERY: Update MYSQL database with form data without refreshing

Ok, so I've gotten most of this thing done.. Now comes, for me, the hard part. This is untreaded territory for me.
How do I update my mysql database, with form data, without having the page refresh? I presume you use AJAX and\or Jquery to do this- but I don't quite grasp the examples being given.
Can anybody please tell me how to perform this task within this context?
So this is my form:
<form name="checklist" id="checklist" class="checklist">
<?php // Loop through query results
while($row = mysql_fetch_array($result))
{
$entry = $row['Entry'];
$CID = $row['CID'];
$checked =$row['Checked'];
// echo $CID;
echo "<input type=\"text\" value=\"$entry\" name=\"textfield$CID;\" id=\"textfield$CID;\" onchange=\"showUser(this.value)\" />";
echo "<input type=\"checkbox\" value=\"\" name=\"checkbox$CID;\" id=\"checkbox$CID;\" value=\"$checked\"".(($checked == '1')? ' checked="checked"' : '')." />";
echo "<br>";
}
?>
<div id="dynamicInput"></div>
<input type="submit" id="checklistSubmit" name="checklistSubmit" class="checklist-submit"> <input type="button" id="CompleteAll" name="CompleteAll" value="Check All" onclick="javascript:checkAll('checklist', true);"><input type="button" id="UncheckAll" name="UncheckAll" value="Uncheck All" onclick="javascript:checkAll('checklist', false);">
<input type="button" value="Add another text input" onClick="addInput('dynamicInput');"></form>
It is populated from the database based on the users session_id, however if the user wants to create a new list item (or is a new visitor period) he can click the button "Add another text input" and a new form element will generate.
All updates to the database need to be done through AJAX\JQUERY and not through a post which will refresh the page.
I really need help on this one. Getting my head around this kind of... Updating method kind of hurts!
Thanks.
You will need to catch the click of the button. And make sure you stop propagation.
$('checklistSubmit').click(function(e) {
$(e).stopPropagation();
$.post({
url: 'checklist.php'
data: $('#checklist').serialize(),
dataType: 'html'
success: function(data, status, jqXHR) {
$('div.successmessage').html(data);
//your success callback function
}
error: function() {
//your error callback function
}
});
});
That's just something I worked up off the top of my head. Should give you the basic idea. I'd be happy to elaborate more if need be.
Check out jQuery's documentation of $.post for all the nitty gritty details.
http://api.jquery.com/jQuery.post/
Edit:
I changed it to use jquery's serialize method. Forgot about it originally.
More Elaboration:
Basically when the submit button is clicked it will call the function specified. You want to do a stop propagation so that the form will not submit by bubbling up the DOM and doing a normal submit.
The $.post is a shorthand version of $.ajax({ type: 'post'});
So all you do is specify the url you want to post to, pass the form data and in php it will come in just like any other request. So then you process the POST data, save your changes in the database or whatever else and send back JSON data as I have it specified. You could also send back HTML or XML. jQuery's documentation shows the possible datatypes.
In your success function will get back data as the first parameter. So whatever you specified as the data type coming back you simply use it how you need to. So let's say you wanted to return some html as a success message. All you would need to do is take the data in the success function and place it where you wanted to in the DOM with .append() or something like that.
Clear as mud?
You need two scripts here: one that runs the AJAX (better to use a framework, jQuery is one of the easiest for me) and a PHP script that gets the Post data and does the database update.
I'm not going to give you a full source (because this is not the place for that), but a guide. In jQuery you can do something like this:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() { // DOM is ready
$("form#checklist").submit(function(evt) {
evt.preventDefault(); // Avoid the "submit" to work, we'll do this manually
var data = new Array();
var dynamicInputs = $("input,select", $(this)); // All inputs and selects in the scope of "$(this)" (the form)
dynamicInputs.each(function() {
// Here "$(this)" is every input and select
var object_name = $(this).attr('name');
var object_value = $(this).attr('value');
data[object_name] = object_value; // Add to an associative array
});
// Now data is fully populated, now we can send it to the PHP
// Documentation: http://api.jquery.com/jQuery.post/
$.post("http://localhost/script.php", data, function(response) {
alert('The PHP returned: ' + response);
});
});
});
</script>
Then take the values from $_POST in PHP (or any other webserver scripting engine) and do your thing to update the DB. Change the URL and the data array to your needs.
Remember that data can be like this: { input1 : value1, input2 : value2 } and the PHP will get something like $_POST['input1'] = value1 and $_POST['input2'] = value2.
This is how i post form data using jquery
$.ajax({
url: 'http://example.com',
type: 'GET',
data: $('#checklist').serialize(),
cache: false,
}).done(function (response) {
/* It worked */
}).fail(function () {
/* It didnt worked */
});
Hope this helps, let me know how you get on!

Running jQuery AJAX in a PHP loop get HTML from a PHP script

I had to ask this one again, sorry. So I am running this jQuery to slide toggle a span in my PHP loops output. I have some PHP that generates some calls to the db to get more detailed information back for each item.
I know so far I have got it making the call to the PHP script. I can see the packets returning with the HTML echoed from the PHP file. but I'm having difficulty getting jQuery to insert the returned data into the specified span.
This is a simplified version of what the loop items look like:
<span class="searchitem">
<span style="visibility:hidden;" class="name">some name</span>
<span class="btn">Details</span>
<span class="itemdetails" style="display: none;">
//hidden area to populate with returned ajax html from php script
</span>
</span>
<span class="searchitem">
<span style="visibility:hidden;" class="name">another name</span>
<span class="btn">Details</span>
<span class="itemdetails">
<div>
<p>
this is the area i need the html to populate
</p>
</div>
</span>
</span>.................
This is the jQuery that I'm trying to run. I know everything works up to success. I can't get the data from there.
<script type="text/javascript">
var ajax_load = "<img src='images/loading.gif' style='width:50px;' alt='loading...' />";
var loadUrl = "ajax/item_details.php";
$(document).ready(function ()
{
$('.searchitem').each(function () {
var itemname = $(this).find('.name').text();
var ename = encodeURI(itemname);
var requestUrl = loadUrl + ename;
$(this).find('.itemdetails').hide();
$(this).find('.btn').click(function ()
{
var returned = "";
$.ajax({
type: "GET",
url: loadUrl,
data: "name=" + ename,
dataType: "text",
error: function () { alert("error") },
success: function (data) { $(".ptavail").append(data); alert("successful") }
});
$(this).parent().find('.ptavail').html(ajax_load).slideToggle(1500).html(returned);
});
});
});
</script>
As you can see from the code I'm trying to get the click function the set everything off. I know the PHP file is receiving the call and returning the data but I'm stuck trying to get the jQuery to fill the .itemdetails with the returned data.
What is wrong with this? Would I need to put the AJAX into a separate function for it to behave like I need, or do I need to make it synchronous for it to work? I'm trying to basically replace everything between .itemdetails spans with first a loading symbol and then the data returned with AJAX.... As it is now I get error alert so there's something wrong with the ajax call I know it does the request properly and the PHP returns the results but getting AJAX to read them is proving problematic.
I can see that the content type in the headers is text, so how do I get the AJAX to do the call properly?
Put $(this).parent().find('.itemdetails').html(ajax_load).slideToggle(1500).html(data);
inside the "success" part of the Ajax request.
success: function(data) {
$(this).parent().find('.itemdetails').html(ajax_load).slideToggle(1500).html(data);
}
The success function is there to say "when the Ajax has worked, do this"

Ajax request inside ajax request fails - reloads the whole page again

So, basicly what I'm trying to achieve:
In index.php
I would enter products code to search for products information and it's images (that query is run in open_first.php, called via ajax post request).
It works just perfect..
When open_first.php is loaded, it displays me some images I can select from (when I click on the image, it's relevant checkbox get's checked containing the image id).
This works too, just fine.
BUT,
If I enter a code in the field: "productCodeCopy" and click on "confirmCodeCopy" -button it reloads the whole page, I mean index.php and everything I've entered is lost and I'm back in the starting point again. I don't understand why it does so. I suppose it has something to do with the fact, that the second ajax request is made from a dynamically created page (open_first.php)?? Do I miss something I should POST too?? Or what's the problem, this is really frustrating me since I've tried to fix this for hours now.
Note:
Jquery is loaded in index.php, open_first.php and open_second.php, I've just ignored that to keep the code simpler.
FILE: index.php (the "starting point")
<!-- head -->
<script type="text/javascript">
$(document).ready(function() {
$("#confirmCode").on('click', function(){
var productCode = $("#productCode").val();
$.ajax({
url: 'open_first.php',
type: "POST",
data: ({code: productCode}),
success: function(data){
$("#found").html(data);
},
error: _alertError
});
function _alertError() {
alert('error on request');
}
});
});
</script>
<!-- body -->
<input type="text" class="textfields" id="productCode" name="productCode" value="YT-6212">
<input type="button" class="admin-buttons green" name="confirmCode" id="confirmCode" value="Search">
<div id="found"></div>
FILE open_first.php
<script type="text/javascript">
$(function() {
$("#foundImage").on('click', function(){
$('#foundImage').toggleClass("foundImage-selected foundImage");
var myID = $('#foundImage').data('image-id');
var checkBox = $('input[id=selectedImages-'+myID+']');
checkBox.prop("checked", !checkBox.prop("checked"));
});
$("#confirmCodeCopy").on('click', function(){
var checkedItems = $('input:checkbox[name="selectedImages[]"]:checked');
// this code here reloads the whole page / view (as in "index.php")
$.ajax({
url: 'open_second.php',
type: "POST",
data: ({checked: checkedItems, copyTo: productCodeCopy, code: "<?php echo $_POST['code']; ?>"}),
success: function(data){
$("#copyToProducts").append(data);
},
error: _alertError
});
/*
// the code below runs just fine when I hit the button "confirmCodeCopy"
alert('Fuu');
return false;
*/
});
function _alertError() {
alert('error');
}
});
</script>
<!--BODY-->
<!-- these are dynamically generated from php, just to simplify we have checkbox that contains value "1" to be posted in ajax -->
<div class="foundImage" id="foundImage" data-image-id="1"><img src="image.jpg"><input type="checkbox" id="selectedImages-1" name="selectedImages[]" value="1" style="display: none;"></div>
<label for="productCodeCopy">Products code</label>
<input type="text" class="textfields" id="productCodeCopy" name="productCodeCopy">
<br /><br />
<label for="confirmCodeCopy"> </label>
<input type="button" class="admin-buttons green" name="confirmCodeCopy" id="confirmCodeCopy" value="Search">
<div id="copyToProducts"></div>
open_second.php only prints out POST variables for now, so nothing special yet.
SOLVED
So ok, I solved it. With dumdum's help.
I removed the line:
$('input:checkbox[name="selectedImages[]"]:checked');
And added this:
var checkedItems = new Array();
var productToCopy = $('#productCodeCopy').val();
$("input:checkbox[name=selectedImages[]]:checked").each(function() {
checkedItems.push($(this).val());
});
Since there was no form element present, it didn't get the field values unless "manually retrieved" via .val() -function.. Stupid me..
I don't know how much this affected but I changed also:
data: ({checked: checkedItems, copyTo: productCodeCopy"})
To
data: {"checked": checkedItems, "copyTo": productToCopy}
So now it's working just fine :) Cool!
WHen you apply event hander to a button or a link to do ajax...always prevent the browser default processing of the click on that element
There are 2 ways. Using either preventDefault() or returning false from handler
$("#confirmCodeCopy").on('click', function(event){
/* method one*/
event.preventDefault();
/* handler code here*/
/* method 2*/
return false;
})
The same is true for adding a submit handler to a form to do ajax with form data rather than having the form redirect to it's action url
your code $('input:checkbox[name="selectedImages[]"]:checked'); is returning undefined making the json data in the ajax call invalid. Check you selector there.

textbox data not available in post variable in php and ajax

I am trying to code a form that has multiple textbox without refershing page using ajax, then after each textbox threre will be link called add which POST call the other php called addnew.php.
In addnew.php data will we added to database(postgres). But I am geting problem while getting the post variable itself.For testing I added the alert in script.
this is my code for form (I will change for multiple textbox once it works fine)
script code
<script type='text/javascript'>
//<![CDATA[
$(window).load(function() {
jQuery(document).ready(function() {
jQuery('.add').live('click', function(event) {
//var da='da='+ $('#da').attr('value');
//var da = 'test';
var da = $('form#myform').serialize();
alert(da);
$.ajax({
type: "POST",
url: "addnew.php",
data:da,
success: function(data) {
if (data === "ok") {
$(this).parent().fadeOut();
$('#results').html(data);
}
else {
alert(data);
}
}
});
});
});
});
//]]>
</script>
form code
<body>
<?php
for ($i=1;$i<2;++$i) {//currently only one textbox for testing purpose
echo "<form name='myform' id='myform'>";
echo "<input name='da' type='text' id='da' value='none'>";
echo "<a href='#' class='add'>Add</a>";
echo "</form>";
}
?>
<div id="results"><div>
</body>
addnew.php code
<? php
if( isset($_POST['da']) )
{
echo (da);
}
?>
when page is rendered will have like this.
<textbox1 data> <add button>
<textbox1 data> <add button>
<textbox1 data> <add button>
...
<textbox10 data> <add button>
what I am trying is
Created each textbox and add button pair inside each form dynamically using for loop.
(for testing i created only one pair).Should I have form for every pair?
when add is clicked value within textbox (#da) should be send to addnew.php through ajax.
following code is displaying data correctly
alert(da);
but in addnew.php file I am not getting $_POST(['da']). Is that means data is not passed to the file or is there something wrong ajax code and finally can I have multiple form with same id. If not then how i can send the only one textbox data ie just before the add button when form is submitted.
You can always dynamically change the target/action of a form element; since you are using jQuery, it would be something like this:
$('#form').attr('action', window.location.href);
That would set a form (with the ID of "form") to have a targeted action of whatever the page URL is. As long as you pass the second argument to attr() you reset the value - this works on basically ANYTHING (you can change a link's href, etc.. all on the fly)
i believe the $(window).load() will not work. the JQuery load method uses ajax to grab data from an url, the url being the first argument of the load method, then it can perform an oncomplete function when it is done loading the ajax response into the calling element. it looks as though you have only put an oncomplete function for the load method, but not the url to be ajaxed. am i mistaken? see http://api.jquery.com/load/
i haven't fully thought it through, but you may just want to remove that first level ($(window).load()), and see what happens then. if you do that, it appears as though the code will add click handlers once the page is "ready".
There is no "submit". Replace your click element:
Add
with a submit button:
<input type="submit" class="add" value="Add" />
or
Add

Categories