I have a simple HTML form where user can search a word from database and PHP return result as a JSON object if the word is in database.
Strange thing is that a JSON object is returned for a word that is in database when user searches by clicking on a button instead of pressing enter key. I have the following two functions to deal with either when user press enter key or click on the button to search. How to improve my code to get the JSON object from PHP when user searches by pressing enter key after they have typed the word in text field?
$('#word-submit').on('click', function() {
var word = $('#word').val();
$.post('ajax/name.php', {word: word}, function(data) {
var obj = jQuery.parseJSON(data);
console.log(obj); //I see the object in Chrome console log.
});
});
$('#word').keypress(function(e) {
if (e.which == 13) {
var word = $('#word').val();
$.post('ajax/name.php', {word: word}, function(data) {
var obj = jQuery.parseJSON(data);
console.log(obj); //No object is return here. Why? May be something is wrong in my code.
});
}
});
<html>
<head>
<title>Welcome</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="container">
<form>
<input type="text" id="word">
<input type="button" id="word-submit" value="Search">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="js/global.js" charset="UTF-8"></script>
</body>
</html>
PHP script works just fine. So I am not pasting it here.
The problem is most likely that your form is submitting. I would just add one listener on the form's submit event which should handle clicking the button and hitting Enter, eg
$(form).on('submit', function(e) {
e.preventDefault(); // don't submit
var word = $('#word').val();
$.post('ajax/name.php', {word: word}, function(data) {
console.log(data);
}, 'json');
});
Ideally, you shouldn't have to parse the JSON or even tell jQuery the response data type (see 'json' arg above). Make sure your PHP script has something like this...
header('Content-type: application/json');
echo json_encode($someDataArrayOrObject);
exit;
In order to make the button work with the above, change its type to submit, ie
<input type="submit" id="word-submit" value="Search">
button work because it prevent the form auto submit / reload it self.
pressing enter key on that textbox causing the form to submit and then reload it self without even triggering the $('#word').keypress(function(e)).
Related
I Have very simple PHP html code for change my website language and I need to use Ajax to not-reload after select language but honestly I never used ajax before and I don't have any idea how to use that.
I google it and found some code but I fail.
HTML:
<form action="" method="get">
<input type="submit" value="per" id="per" name="per">
<input type="submit" value="eng" id="eng" name="eng">
</form>
PHP :
function lang()
{
$lang = 'per';
if (isset($_GET['per']))
return $lang = 'per';
else
return $lang = 'eng';
}
Ajax:
$.ajax({
type: "GET",
url: 'index.blade.php',
data: {name: 'per'},
success: function(data){
alert(data);
window.location.reload();
}
});
All Code's are at one page named
index.blade.php
php code working fine just need for ajax to not-reload page when I click buttons
Try this:
html:
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<form action="" >
<button type="submit" id="button1">Click
</button>
</form>
<script type="text/javascript" src="1.js"></script>
<!--<script type="text/javascript" src="2.js"></script>-->
</html>
js:
document.getElementById("button1").addEventListener("click",function(e){
//alert("hello");
e.preventDefault(); //a button's default behavior is to submit the form which this function prevents
$.ajax({
url:"example.php",
success:function(result){
alert(result);
location.href=location.href; //here you can specify where you want to get your ajax call to redirect to.
}
})
return false;
})
php file:
<?php
echo "Hello world";
?>
Hope this is what you are looking for!
I suggest studying a few tutorials on Ajax, I will try to briefly touch the subject here.
First of all, when doing Ajax, you basically call a web page or script (an actual url, not a function written in PHP). The result that you get (HTML, XML, CSS, JSON, JPG), you can use in your code, insert ii in the DOM, change the document, etc.
In my opinion, changing the language is a site-wide action that should probably be implemented as a normal call. Genearaly, if you change the language, then the whole page should be translated, from the top (title) to the last bit of text down before the closing body.
If you just need to change a small portion of the web page, please see the URL
jQuery get
The page uses an example
$.get( "ajax/test.html", function( data ) {
$( ".result" ).html( data );
alert( "Load was performed." );
});
that performs what you want, just change the url. Hope I helped a bit.
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
How to make jAlert() Message Box without OK Button.
Basically what I want is to use jAlert() like Jquery Block UI
Please check this fiddle http://jsfiddle.net/Bumts/2/.
There has been some modifications in the core jquery.alert.js, since there has been no overlay param. I made the changes to pass overlay (6th parameter) option to pass for it. You could replace the jquery.alert js code with my modified one.
$(function(){
$('#test').click(function(){$('#test3').jAlert('This is a jAlert Warning Box',"warning",'warningboxid', '', '', 1);});
});
Use JQuery events !!
Example ::
Case 1 : If you are trying to trigger your button after an interval
then use
setInterval( "clickRight()", 5000 );
function clickRight()
{
$('.slide_right').trigger('click');
};
Case 2 : If you are waiting for user to type some thing on to an input field
$('#form').on('mousedown',function(e)
{
if(e.which===1)
{
//call your function alerting message here//
}
}
Short Code ::
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<input id="whichkey" value="type something">
<div id="log"></div>
<script>
$('#whichkey').on('mousedown',function(e){
alert("Error");
});
</script>
</body>
</html>
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.
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?
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