How to share data between programming languages - javascript

Hypothetical here: Let's say that you have a JavaScript file that uses jQuery to get input from the user. For example:
var $input = 0;
var buttonClick = function() {
$('.button').click(function() {
$input = $('input').val();
});
}
$(document).ready(buttonClick());
But what if you want to use sql to see if the input matches a password in a database
How would you tell the sql script to run after you click the button?
How would you share the $input variable the sql script so it could check it against the database?

var buttonClick = function() {
$('.button').click(function() {
$.post( "script.php", { Username: "Your Name", Password: "Password" })
.done(function( data ) {
alert( "Data Send: " + data );
// In data you have a response you got from the php script
});
});
}

If you wan't to check Password when your client click on the button , you need to use Ajax and call a Php function.
So when your client click on the button, Jquery call the PHP script and the PHP script call Mysql. After Mysql give a response to Php who send Data to Jquery (true or false in this case).

Related

jQuery/Javascript: Efficient method to check user text input against a very large list of possible cases

I have created a 'check if we deliver to you' button on my site in jQuery.
The postcodes are put into an array, and the user input is checked against the array when the form is submitted.
There are approx. 10,000 postcodes to check against - which creates quite a large js file.
It seems to work no problem, but I expect this is not the best way of doing it.
I found this example, but this also includes all the values in the js file:
Jquery Validator - check input against a list of accepted values
// post code check
jQuery(function($) {
// if user presses enter
if ($('.home').length) {
$('#postcode').keypress(function(e) {
if (e.which == 13) {
e.preventDefault();
$('#submit').click();
};
});
$("#submit").click(function(e) {
e.preventDefault();
var trim = $("#postcode").val();
var val = trim.replace(/ /g, '');
var upper = val.toUpperCase();
var test = ["hello"]
var arr = ["postcode1", "postcode2", "...postcode10,000"];
if ($.inArray(upper, arr) !== -1) {
alert('We Deliver To You!');
} else {
alert('Sorry we are not in your area yet');
};
});
};
});
You probably need to send ajax to backend and check in db if current postcode is available to shipping. So you need :
backend script to catch request
table is db with all possible postcodes and flag(available or not)
send ajax request to backend script
sql table for postcodes(example)
CREATE TABLE `postcodes` (
`code` INT NOT NULL AUTO_INCREMENT,
`status` ENUM('NORMAL','DISABLED') NULL DEFAULT 'NORMAL',
`created_at` INT NULL,
`updated_at` INT NULL,
PRIMARY KEY (`code`));
simple jQuerycode to send ajax:
$.ajax({
method: "POST",
url: "some.php",
data: { postCode:"some code"}
})
.done(function( html ) {
alert( "$.ajax done" );
console.log(html)
});

Can I include a php sql update within my javascript?

I am trying to use a combination of javascript and php to update a column within a sql database when a form gets submitted. The name of the sql database is "answers," the name of the column within the database is "FunctionsConsistency," and the form's id is "easytohard." I'm not sure, however, if it's possible to include the php (noted below by the asterisks) within this javascript code.
<script type='text/javascript'>
$(document).ready(function () {
$('#easytohard').on('submit', function(e) {
e.preventDefault();
$.ajax({
url : $(this).attr('action') || window.location.pathname,
type: "POST",
data: $(this).serialize(),
success: function (data) {
******THIS IS THE PHP CODE*********
$stmt = $db->prepare("UPDATE answers SET FunctionsConsistency = 1
WHERE id = ? AND FunctionsConsistency = 0") or die($db->error);
$stmt->bind_param("i", $id);
$stmt->execute();
******************
},
});
});
});
</script>
Thanks!
You can't mix Javascript and PHP like that.
Php should be executed on the server side while javascript meant to be executed on the client side.
You can put the Php file on your server, and just send the request to it using ajax or whatever.
Something like:
<script type='text/javascript'>
$(document).ready(function () {
$('#easytohard').on('submit', function(e) {
e.preventDefault();
$.ajax({
url : $('http://path/to/your/php/file/on/server'),
type: "POST",
data: {id: 'your desired id here'},
success: function (data) {
// if it reach this line, it means script on the php file is executed
},
});
});
});
</script>
And your php file should be on your server (path: http://path/to/your/php/file/on/server), containing proper includes to work.
<?php
$stmt = $db->prepare("UPDATE answers SET FunctionsConsistency = 1
WHERE id = ? AND FunctionsConsistency = 0") or die($db->error);
$stmt->bind_param("i", $_POST['id']);
$stmt->execute();
Notice you can access to post parameters using $_POST in php.
There are still a few things you should consider, for example when the requests don't reach to server or what if server fail to execute php file ..., but you got the idea.
Also, take a look at this and this. Hope this helps.

checking instantly php arrays using jquery / ajax

I want to be able to check whether values exist in the php array without having to click the submit button to do those checks using jquery/ajax.
when users enter an abbreviation in the text field want to be able to show that the brand exists (either vw or tyta) or not (as they type in the input box) and show the results in the carnamestatus div.
I was following a tutorial from youtube, however it queried against a mysql database.
I was wondering if this is possible using php arrays instead of mysql? I would be grateful if you could pick any faults in the code.
the code is as follows:
<?php
$car = array()
$car["vw"] = array( "name" => "volkswagen");
$car["tyta"] = array( "name => "toyota");
?>
the html code is as follows:
<label for="carname">Car Code:</label> <input type="text" onblur="checkcar()" value="" id="carname" />
<div id="carnamestatus"></div>
the checkcar()
function checkcar(){
var u = _("carname").value;
if(u != ""){
_("carname").innerHTML = 'checking ...';
var B = new XMLHttpRequest();
B.open("POST","check.php",true); /
B.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
B.onreadystatechange = function() {
if(B.readyState==4 && B.status== 200) {
_("carnamestatus").innerHTML = B.responseText;
}
}
var v = "carnamecheck="+u;
B.send(v);
}
}
</script>
Use Javascript keyboard event and then, send the value of the input into your php function.
For example:
$("#youInput").keyup(
function() {
$.ajax(
{
type: "post",
url: "your_url.php",
data: {params: $(this).val()},
success: function(data) {
console.log(data)
}
}
);
}
);
And in you php code, just retrieve the params value, $_POST['params']
Explain
When you press the keybord, your retrieve the value of the input ( here, it is $(this).val() where this represents #yourInput ), then you send the value via ajax (Here we use post type) with your url and the different params that you will send to the server side. If you post the value with $_POST['params'] you will get the value entered in the input. And if it's success, the callback function will retrieve the data returned by your server side.
Here, we just use, jQuery.ajax but you can find more about ajax here or here. Using library make it easy to work with.
Hope it helps you!

Passing values from jQuery to PHP in same page instantly

I have written a PHP program to confirm deletion of data through jQuery confirm message (Refer: http://rathur.fr/jQuery/MsgBox/) and record the result back to the same page itself instantly. If the page refreshes, it'll return back its state to previous.
The part of line is below:
print "
<script type='text/javascript'>
$(document).ready(function(){
$.msgbox('<br/>Are you sure you want to delete the selected record from the database?', {
type : 'confirm'
}, function(result){
$('#output').text(result);
var output = result;
});
});
</script>";
I want to get the result of the action button to PHP variable instantly, like below (just a trial):
$x = $_SESSION['output']; OR
$x = $_POST['output']; OR
$x = print "<div id=\"output\"></div>"; OR
$x = some_function(output);
Please help me, or suggest if there is other better options.
Here is a simple Ajax call to a Php File by an event : Click on a button.
Javascript client side :
$("body").on("click", "#mybutton", function() {
var mydata = $("#form").serialize();
$.ajax({
type: "POST",
url: "/api/api.php",
data: {data : mydata},
timeout: 6e3,
error: function(a, b) {
if ("timeout" == b) $("#err-timedout").slideDown("slow"); else {
$("#err-state").slideDown("slow");
$("#err-state").html("An error occurred: " + b);
}
},
success: function(a) {
var e = $.parseJSON(a);
if (true == e["success"]) {
$("#action").html(e['message']);
// here is what you want, callback Php response content in Html DOM
}
}
});
return false;
});
Next in your Php code simply do after any success function :
if ($result) {
echo json_encode(array(
'success' => true,
'msg' => "Nice CallBack by Php sent to client Side by Ajax Call"
));
}
You should use jQuery to POST the data to a PHP script using AJAX if you want to use the second pass.
http://api.jquery.com/category/ajax/ has many functions and tutorials on writing AJAX functions and handling return data. In particular, look at the post() function.

Save form data using AJAX to PHP

How can I save the form data in a file or a local db (maybe using AJAX) which send the data via form action to an external db?
The source code for my form is here: http://jsbin.com/ojUjEKa/1/edit
What changes (if any) should I make to the code?
EDIT:
Right. So I'm able to store the data into localStorage using AJAX and want to send the data stored across to a file called backend.php. Here's my html file: http://jsbin.com/iSorEYu/1/edit
and here's my backend.php file: http://jsbin.com/OGIbEDuX/1/edit
The AJAX is working absolutely fine to store the fields in localStorage but things go wrong when it tries to send the data across to backend.php. I receive the following errors:
[24-Jan-2014 08:40:34 America/Chicago] PHP Notice: Undefined index: data in /home4/private/public_html/marketer/backend.php on line 7
[24-Jan-2014 08:40:34 America/Chicago] PHP Warning: Invalid argument supplied for foreach() in /home4/private/public_html/marketer/backend.php on line 10
[24-Jan-2014 08:40:58 America/Chicago] PHP Notice: Undefined index: data in /home4/private/public_html/marketer/backend.php on line 7
[24-Jan-2014 08:40:58 America/Chicago] PHP Warning: Invalid argument supplied for foreach() in /home4/private/public_html/marketer/backend.php on line 10
What's the issue here?
LocalStorage would be your best bet. I would suggest using storejs as their API is straight forward, easy to use, and x-browser.
You could then trigger the form values to be stored on the "blur" event of each field.
$('input').on('blur', function (e) {
var el = e.target;
store.set(el.attr('name'), el.val());
});
When you are ready to submit to the server, you could use something like the following:
$('#formID').on('submit', function (e) {
e.preventDefault();
$.post('/my/save/route', store.getAll(), function () { ... });
});
You of course could do all of this without storejs and use vanilla JS to interact with the native LocalStorage API.
PHP:
<h1>Below is the data retrieved from SERVER</h1>
<?php
date_default_timezone_set('America/Chicago'); // CDT
echo '<h2>Server Timezone : ' . date_default_timezone_get() . '</h2>';
$current_date = date('d/m/Y == H:i:s ');
print "<h2>Server Time : " . $current_date . "</h2>";
$dataObject = $_POST; //Fetching all posts
echo "<pre>"; //making the dump look nice in html.
var_dump($dataObject);
echo "</pre>";
//Writes it as json to the file, you can transform it any way you want
$json = json_encode($dataObject);
file_put_contents('your_data.txt', $json);
?>
JS:
<script type="text/javascript">
$(document).ready(function(){
localStorage.clear();
$("form").on("submit", function() {
if(window.localStorage!==undefined) {
var fields = $(this).serialize();
localStorage.setItem("eloqua-fields", JSON.stringify( fields ));
alert("Stored Succesfully");
$(this).find("input[type=text]").val("");
alert("Now Passing stored data to Server through AJAX jQuery");
$.ajax({
type: "POST",
url: "backend.php",
data: fields,
success: function(data) {
$('#output').html(data);
}
});
} else {
alert("Storage Failed. Try refreshing");
}
});
});
</script>

Categories

Resources