is it possible to use jquery.post for 2 level what i mean is (the secod $.post depends on the first one )
let's assume that a company have a phone number, name and description (for the sake of this example)
<body>
// retrieving companies that have a name similar (or contains )
// what is written in the input box bellow :
<form method="POST" id="searchForm">
<input type="text" name ="name" id="name">
<input type="submit" value="Find">
</form>
// when the user enter a name in the input and submit the form
// with out refreshing the page (adding return false to the jquery click function)
// we will display all retrieved company code inside <ul>(using loop for example)
<ul id="companies_list">
<li id="company"><input type="hidden" value="[company code goes here ]>
<span>[company name goes here]</span><li>
</ul>
// the user select the desired company name (li item )
// and then without refreshing the page we will display the information
// about the selected company in the company_details area
<div id="company_details">
[here goes the selected company details]
</div>
jquery code :
$(document).ready(function(){
// when the dom is ready start manipulating
$("#searchForm").submit(function(event){
// stop form from being submited normaly
event.preventDefault();
// sendig post data
var name = $("input[type="text"]").val();
var url = "ajax/search.php";
var posting = $.post( url, {name:name} );
posting.done(function(data) {
// assuming the data holds companies list (ie: <li>c1</li><li>c2</li>)
$("#companies_list").html(data);
});
});
// the last part (below) does'not work for me
$("#company").click(function(){
var code = [ company code stored in hidden field]
var url = 'ajax/detail';
var posting1 = $.post(url,{code:code});
posting1.done(function(data){
put the result in the company_details div
$("#company_details").html(data)
});
return false;
});
});
Yes, the third argument to $.post is function that is executed when post successfuly completes. So the code would be:
$(document).ready(function(){
// when the dom is ready start manipulating
$("#searchForm").submit(function(event){
// stop form from being submited normaly
event.preventDefault();
// sendig post data
var name = $("input[type="text"]").val();
var url = "ajax/search.php";
var posting = $.post( url, {name:name}, function(data) {
// assuming the data holds companies list (ie: <li>c1</li><li>c2</li>)
$("#companies_list").html(data);
} )
});
Related
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
I am foreaching a number of suppliers in a quotation form, each with a checkbox element to tick which should be contacted. suppliers are in divs with class names supplier-checkbox, moreover upon selecting supplier the supplier-checkbox div gets appended with "checkedsupplier" or "uncheckedsupplier" class name.
<div class="supplier-checkbox checkedsupplier">
<input type="hidden" name="supplier-email" class="supplieremail" value="{$item->email}" />
</div> <!--end supplier checkbox-->
foreach supplier div I get a hidden input field within the div holding the supplier email as its value. idea is that upon submitting form I'd check for all div's with "checkedsupplier" class name and for each obtain the value of the input inside of it, hold all values in onelong variable and echo it into the To field of the email to replicate the quotation form to each supplier.
using jquery, I managed to toggle the class name and a background effect showing ticked or unticked with the below.
<script>
$(".supplier-checkbox").click(function(){
$(this).toggleClass('checkedsupplier uncheckedsupplier')
//$(this).children( ".supplieremail" ).attr("checked")
});
</script>
can anyone give me any pointers on how to foreach by class name and fetch value of each input inside every div with that class name using jquery. Im working on it and yet found the .each for looping .val for values and if (bar) for conditional. but am not yet experienced enough to put things together. have been working as a junior developer for 7 months now since graduating in networking which is a completely different field.
in the app.js file I'm obtaining the form values this way:
`
v_country:$('#country').val(),
v_quotationtel:$('#quotationtel').val(),
v_mobile:$('#mobile').val(),
v_quotationemail:$('#quotationemail').val(),
v_quotemefor:$('#quotemefor').val(),
v_quotemessage:$('#quotemessage').val()
//this line is what i'm trying to do to get input values and store them in one var to pass them to php form that sends email $( "checksupplier" ).each(function( i ) {
}`
thanks everyone on stack! I believe in you guys here you've all helped me throughout my studies and work.
Ian
** Update ** It's been modified to work as follows:
<script>
$(function(){
$( ".crew-member-con" ).click(function(){
$(this).toggleClass('whitebg greybg');
$(this).toggleClass('crew-checked crew-unchecked');
$(this).toggleClass('grey white');
if($(this).children('input').prop('checked') == true){
$(this).children('input').prop('checked', false);
}else{
$(this).children('input').prop('checked', true);
}
var selectedMembers='';
$('.selected-members').each(function(){
if($(this).is(':checked')){
selectedMembers +=$(this).val()+', ';
}
//alert(emails);
});
if(selectedMembers != ''){
selectedMembers = selectedMembers.slice(0,-2);
}
$('#exam-member span').html(selectedMembers);
console.log(selectedMembers);
});
});
Here's an example with some notes.
$('.myform').submit(function () {
getEmailAddresses();
return false;
}
function getEmailAddresses () {
// a place to hold them
var emails = new Array();
// what will be after 'mailto'
var emailsString = "";
// get 'em
$('.checkedsupplier').each(function () {
// get the hidden email input value
var email = $(this).find('.supplieremail').val();
// check, just in case;
if (email) {
// push the value into our array
emails.push(email);
}
});
//put them all together into a string, split by a semi-colon
emailsString = emails.join(';');
// finally, stuff our mail to link.
// Not sure what you're plan is here but 'emailsString' has all of the values you eed.
$('.mailtolink').attr('href', 'mailto:'+emailsString);
}
<script>
$(".supplier-checkbox").click(function(){
$(this).toggleClass('checkedsupplier uncheckedsupplier')
//$(this).children( ".supplieremail" ).attr("checked")
var emails='';
$('.supplieremail').each(function(){
emails +=$(this).val();
});
$('#mailfieldstextarea').val(emails);
});
</script>
I hope this will help.
I have a form that contains multiple inputs, and each input has its own respective button. I'm looking to have each button insert the adjacent input's typed value into a new browser tab and opens that address on click of the button.
Let’s say I type 121680573 into the text field, and when I click the button next to the field, this address should be opened in a new tab:
a810-bisweb.nyc.gov/bisweb/JobsQueryByNumberServlet?passjobnumber=121680573&passdocnumber=&go10=+GO+&requestid=0
The typed value would have to be inserted into that specific position after the = sign.
Thus far this is the only code I've come up with to accomplish this task (I created an alert for the sake of this example being I don't know how to accomplish the insertion of text). #bis represents the button:
$(document).ready() {
var bis_button = $('.bis_button');
bis_button.click(function() {
alert(bis_button.val());
});
});
The inputs and buttons are arranged like this in a WordPress page. Each input is assigned an ID by the WordPress plugin that's creating the page:
<div id="frm_field_[id]_container" class="frm_form_field form-field [required_class][error_class]">
<label class="frm_primary_label">[field_name]
<span class="frm_required">[required_label]</span>
</label>
[input]
[if description]<div class="frm_description">[description]</div>[/if description]
[if error]<div class="frm_error">[error]</div>[/if error]
<div class="bis_button">View in BIS</div>
</div>
I've attached an image that shows the fields and their respective buttons.:
$(document).ready(function() {
$(".bis_button").click(function() {
var inputValue = $(this).parent('.frm_form_field').find('input').val();
window.open('a810-bisweb.nyc.gov/bisweb/JobsQueryByNumberServlet?passjobnumber='+inputValue+'&passdocnumber=&go10=+GO+&requestid=0');
})
});
You should be able to do this:
bis.click(function() {
var prefix = "a810-bisweb.nyc.gov/bisweb/JobsQueryByNumberServlet?passjobnumber=";
var suffix = "&passdocnumber=&go10=+GO+&requestid=0"
var url = prefix + $(this).siblings("input[type='text']").val() + suffix;
window.open(url,'_blank');
});
On my Code I have this callback
$('#tagList').tagit({
//Every new dag will be pushed in the list array
tagsChanged: function(tagValue,action,element){
list.push(tagValue);
$.ajax({
url: "dostuff.php",
type: "POST",
data:{ items:list.join("::")},
success: function(data){
$('#wrap').append(data);
}
});
}
});
What it does it that each time I add a tag the newly added tag will be pushed in the array and after that it will make an AJAX post request.
And Then i have these field here
<form method = "POST" action = "demo3.php">
News Title <input id = "news_title" type = "text" name = "news_title" /><br>
<label>Insert Some tags </label>
<ul id="tagList" data-name="demo2">
</ul>
<input type = "submit" name = "submit" id = "submit" value = "Post News" />
</div>
</form>
and when I click the submit(it basically reloads the page) the $_POST['items'](This was created on AJAX request everytime a new tag is added) is being erased or removed in the POST global array. and therefore leaving my $_POST global array empty.
Is there anyway I can merge these two? or anyway not to let PHP override or remove the $_POST['items'] ?since I would be needing items for my query
Also I am using a plugin called tagit
If you guys are interested here's my whole code
<!doctype html>
<html>
<head>
<script src="demo/js/jquery.1.7.2.min.js"></script>
<script src="demo/js/jquery-ui.1.8.20.min.js"></script>
<script src="js/tagit.js"></script>
<link rel="stylesheet" type="text/css" href="css/tagit-stylish-yellow.css">
<script>
$(document).ready(function () {
var list = new Array();
$('#tagList').tagit({
//Every new dag will be pushed in the list array
tagsChanged: function(tagValue,action,element){
list.push(tagValue);
$.ajax({
url: "dostuff.php",
type: "POST",
data:{ items:list.join("::")},
success: function(data){
$('#wrap').append(data);
}
});
}
});
});
</script>
</head>
<body>
<div id="wrap">
<div class="box">
<button class = "viewTags">View Tags</button>
<form method = "POST" action = "demo3.php">
News Title <input id = "news_title" type = "text" name = "news_title" /><br>
<label>Insert Some tags </label>
<ul id="tagList" data-name="demo2">
</ul>
<input type = "submit" name = "submit" id = "submit" value = "Post News" />
</div>
</form>
</div>
</body>
</html>
and here's dostuff. php
<?php
$lis = $_POST['items'];
$liarray = explode("::", $lis);
print_r($liarray);
print_r($_POST);
?>
The way PHP handles requests are that every request is completely separated from every other one, this sometimes referred as the share nothing architecture. This is the reason of that the request generated from the <form> to demo3.php doesn't know about the other requests sent by ajax to dostuff.php is this separation. This is not necessarily php specific, it's because the underlying HTTP protocol is stateless.
If you want to include tags into the request generated when your <form> is submitted you need to add those values to the form. For this, the tagit library has a built in way controlled by two config option:
itemName controls what the parameter named (defaults to item)
fieldName controls what the field in the itemName gets called (defaults to tags)
If you initialize your plugin like this (demo without styles):
$('#tagList').tagit({
itemName: 'article',
fieldName: 'tags'
});
Then on submit, the parametes sent down to php should be in $_POST['article']['tags'], the parameter names generated will look like article[tags][]. See the demos of the plugin. (the page source has nicely formatted javasript examples). By default simply calling $('#tagList').tagit(); without all the extra callbacks or configuration should work.
This is how it should show up in the net panel of firebug (never mind the demo4.php not beeing there)
If you want to do it manually you can hook into the submit event of <form> like this:
$('form').on('submit', function(){
var $form = $(this),
tags = $('#tagList').tagit('assignedTags'); // see the docs https://github.com/aehlke/tag-it/blob/master/README.markdown#assignedtags
$.each(tags, function(i, tag){
$('<input type="hidden" name="tags[]">').attr('value', tag).appendTo($form); // using jquery to create new elements
});
});
By using the assignedTags method (with jquery ui calling schema) of the tagit plugin, you can get the tag names, and simply add a new hidden input just before submitting the <form>. Joining them together like this might be a bad idea if your can include any string imaginable even ::.
In the example, i've used separate input for each tag so in your demo3.php they will arrive as an array (ending the name with [] makes php do that).
I have a web page that lists a number of companies from a MYSQL database, the listing just shows the name of the company. When user clicks on the company name a jquery accordion slider shows the rest of the information about that company.
When company name is clicked it also sends a request to a php script to log that a person has viewed that company's details.
My Problem
I want to send the ID for each record to the php script.
I have achieved this by including the accordion jquery code within the while loop that reads the output of the mysql query, but it generates a lot of unnecessary source code (i.e. for each company listed).
I need to include the jquery accordion code outside of the while statement.
How do I pass the id of each database record (i.e. company name) to the $.post in the jquery code, when it is outside of the while loop?
Accordion Jquery code
$(document).ready(function() { $('div.listing> div').hide(); $('div.listing> h4').click(function() {
$.post("/record.php", { id: "<?php echo $LM_row02[id]; ?>" } )
var $nextDiv = $(this).next();
var $visibleSiblings = $nextDiv.siblings('div:visible');
if ($visibleSiblings.length ) {
$visibleSiblings.slideUp('fast', function() {
$nextDiv.slideToggle('fast');
});
} else {
$nextDiv.slideToggle('fast');
} }); });
Any idea most welcome.
When you create the HTML (I assume you do that in the loop as well), add a data-* attribute with the ID as value to the element and read that value with jQuery when the element is clicked on.
E.g. your resulting HTML will look like:
<h4 data-id="123">Some title</h4>
and your JavaScript:
$('div.listing > h4').click(function() {
$.post("/record.php", { id: $(this).attr('data-id') }, function() {
// ...
});
});
When you create the h4 element in html add a html5 data attribute like
<h4 data-companyid="<?php echo $LM_row02[id]; ?>">Company Name</h4>
Then use that companyid in your ajax call like
$.post("/record.php", { id: $(this).data('companyid') } );