I have a JavaScript confirm box and i have some MySQL insert query code to be executed at some condition. This is how my code look like:
<?php
$id = $_POST['id'];
$name= $_POST['name'];
$query = mysql_query("select * from table where id='$id'");
$count = mysql_num_rows($query );
if($count!=0)
{
?>
<script type="text/javascript">
if (confirm("This seems to be Duplicate. Do you want to continue ?") == true)
{
//Execute/Insert into table as how it is given below
}
else
{
//Dont execute/insert into table but close the window
}
</script>
<?php
}
else
{
$queryinsert = mysql_query("INSERT INTO table(id,name) VALUES('$id','$name')");
}
?>
You can't execute MySQL or PHP command inside javascript, what you can do instead is to make a PHP function that you can call by Ajax. The best way is by using jQuery or by redirecting the page with your PHP function in URL.
<script type="text/javascript">
if (confirm("This seems to be Duplicate. Do you want to continue ?"))
{
$.ajax({
url: 'your_path_to_php_function.php',
type: 'POST', // Or any HTTP method you like
data: {data: 'any_external_data'}
})
.done(function( data ) {
// do_something()
});
}
else
{
window.location = 'your_url?yourspecialtag=true'
}
</script>
You're mixing serverside and clientside scrips. This won't work. You have to use AJAX, which are asynchronous server-client/client-server requests. I recommend jQuery, which is JavaScript which easily handles lot of things, including AJAX.
Run this if user confirms action
$.post("phpscript.php", {action: true})
Php file:
if ($_POST['action'] === TRUE) {
<your code here>
}
Related
I want to manipulate the value that it is stored in this variable $result[]. Specifically i want to return that value from php file to my html file. What should i do? Can you give me some reference code when i want to return things from server side to client side for further manipulation?
My php file:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("127.0.0.1", "root", "", "mysql3");
// Check connection
if($link === false) {
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$user_id =$_POST['user_id'];
$book_id =$_POST['book_id'];
$game_id =$_POST['game_id'];
$site_id =$_POST['site_id'];
//Attempt insert query execution
$query = "SELECT site_id FROM components WHERE user_id='$user_id' && book_id='$book_id' && game_id='$game_id' ORDER BY site_id DESC LIMIT 1";
$res = mysqli_query($link,$query);
$result = array();
$res = mysqli_query($link,$query) or die(mysqli_error($link));
while($row = mysqli_fetch_assoc($res)){
$result[]=$row['site_id'];
}
// Close connection
mysqli_close($link);
?>
My html file:
<html>
<head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
<script>
function load3() {
var flag1 = true;
do{
var selection = window.prompt("Give the User Id:", "Type a number!");
if ( /^[0-9]+$/.test(selection)) {
flag1=false;
}
}while(flag1!=false);
$("#user_id").val(selection)
//$("#user_id").val(prompt("Give the User Id:"))
var flag2 = true;
do{
var selection2 = window.prompt("Give the Book Id:", "Type a number!");
if ( /^[0-9]+$/.test(selection2)) {
flag2=false;
}
}while(flag2!=false);
$("#book_id").val(selection2)
//$("#book_id").val(prompt("Give the Book Id:"))
var flag3= true;
do{
var selection3 = window.prompt("Give the Game Id:", "Type a number!");
if ( /^[0-9]+$/.test(selection3)) {
flag3=false;
}
}while(flag3!=false);
$("#game_id").val(selection3)
//$("#game_id").val(prompt("Give the Game Id:"))
}
var fieldNameElement = document.getElementById('outPut');
if (fieldNameElement == 4)
{
window.alert("bingo!");
}
</script>
</head>
<body>
<form name="LoadGame" id="LoadGame" method="post" action="http://127.0.0.1/PHP/mine1.php" enctype="multipart/form-data">
<input type="submit" value="Load" id="load" onclick="load3()" class="button12" />
<input type="hidden" name="user_id" id="user_id">
<input type="hidden" name="book_id" id="book_id">
<input type="hidden" name="game_id" id="game_id">
<input type="hidden" name="site_id" id="site_id">
</form>
</body>
</html>
Note that this answer is making use of jQuery notation, so you will need to include a jQuery library in your application in order to make this example work:
<script src="/js/jquery.min.js" type="text/javascript"></script>
Since you have your HTML and PHP in separate files, you can use AJAX to output your HTML in an element you so desire on your HTML page.
Example of jQuery AJAX:
<script>
function submitMyForm() {
$.ajax({
type: 'POST',
url: '/your_page.php',
data: $('#yourFormId').serialize(),
success: function (html) {
//do something on success?
$('#outPut').html(html);
var bingoValue=4;
if( $('#outPut').text().indexOf(''+bingoValue) > 0){
alert('bingo!');
}
else {
alert('No!');
}
}
});
}
</script>
Note that I encapsulated the AJAX function in another function that you can choose to call onclick on a button for example.
<button id="mySubmitButton" onclick="submitMyForm();">Submit form!</button>
Step-by-step:
What we do in our AJAX function, is that we declare our data type, just like you would do with a form element. In your PHP file I noticed that you used the POST method, so that's what I incorporated in the AJAX function as well.
Next we declare our URL, which is where the data will be sent. This is the same page that your current form is sending the data to, which is your PHP page.
We then the declare our data. Now, there are different ways of doing this. I assume you are using a form currently to POST your data to your PHP page, so I thought we might as well make use of that form now that you have it anyways. What we do is that we basically serialize the data inside your form as our POST values, just like you do on a normal form submit. Another way of doing it, would be to declare individual variables as your POST variables.
Example of individual variables:
$.ajax({
type: 'POST',
url: '/your_page.php',
data: {
myVariable : data,
anotherVariable : moreData
//etc.
},
success: function (html) {
//do something on success?
$('#outPut').html(html);
}
});
A literal example of a variable to parse: myVariable : $('input#bookId').val().
The operator : in our AJAX function is basically an = in this case, so we set our variable to be equal to whatever we want. In the literal example myVariable will contain the value of an input field with the id bookId. You can do targeting by any selector you want, and you can look that up. I just used this as an example.
In the success function of the AJAX function, you can basically do something upon success. This is where you could insert the HTML that you wish to output from your PHP page into another element (a div for example). In my AJAX example, I am outputting the html from the PHP page into an element that contains the id outPut.
We also write a condition in our success function (based off comments to this answer), where we check for a specific substring value in the div element. This substring value is defined through the variable bingoValue. In my example I set that to be equal to 4, so whenever "4" exists inside the div element, it enters the condition.
Example:
<div id="outPut"></div>
If you make use of this example, then whatever HTML you structure in your PHP file, making use of the PHP values in your PHP file, will be inserted into the div element.
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("127.0.0.1", "root", "", "mysql3");
// Check connection
if($link === false) {
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$user_id =$_POST['user_id'];
$book_id =$_POST['book_id'];
$game_id =$_POST['game_id'];
$site_id =$_POST['site_id'];
//Attempt insert query execution
$query = "SELECT site_id FROM components WHERE user_id='$user_id' && book_id='$book_id' && game_id='$game_id' ORDER BY site_id DESC LIMIT 1";
$res = mysqli_query($link,$query);
$result = array();
$res = mysqli_query($link,$query) or die(mysqli_error($link));
while($row = mysqli_fetch_assoc($res)){
$result=$row['site_id'];
echo $result.' ';
}
// Close connection
mysqli_close($link);
?>
Your form also no longer needs an action defined as all of that is now taken care of by the AJAX function.
So change:
<form name="LoadGame" id="LoadGame" method="post" action="http://127.0.0.1/PHP/mine1.php" enctype="multipart/form-data">
to:
<form name="LoadGame" id="LoadGame" method="post" enctype="multipart/form-data">
And make sure that your button: <button id="mySubmitButton" onclick="submitMyForm();">Submit form!</button> is outside of your form tag, as buttons without a defined type attribute will have type="submit" by default inside a form tag.
If you need anything elaborated, let me know. :)
First of all: remove the script tag from your php.
Secondly: Why are you executing the sql statement two times?
To your question:
You have to send a request to your PHP script via AJAX: (Place this inside <script> tags and make sure to include jquery correctly)
$(() => {
$('form').on('submit', () => {
event.preventDefault()
$.ajax({
type: 'POST',
url: '<your-php-file>', // Modify to your requirements
dataType: 'json',
data: $('form').serialize() // Modify to your requirements
}).done(function(response){
console.log(response)
}).fail(function(){
console.log('ERROR')
})
})
})
Your PHP-Script which needs to return JSON:
$query = "SELECT site_id FROM components WHERE user_id='$user_id' && book_id='$book_id' && game_id='$game_id' ORDER BY site_id DESC LIMIT 1";
// Execute Query
$res = mysqli_query($link,$query) or die(mysqli_error($link));
// Get Rows
while($row = mysqli_fetch_assoc($res)){
$result[] = $row['site_id'];
}
// Return JSON to AJAX
echo json_encode($result);
Take a look at your developer console.
Haven't tested it.
I'm trying to add ajax autosave to my settings page in plugin and made this code:
<?php
function cfgeo_settings_javascript() { ?>
<script type="text/javascript" >
(function($){
$(document).ready(function(){
$("input[id^='cf_geo_'], select[id^='cf_geo_'], textarea[id^='cf_geo_']").on("change keyup", function(){
var This = $(this),
name = This.attr("name"),
value = This.val(),
data = {};
data['action'] = 'cfgeo_settings';
data[name] = value;
console.log(data);
console.log(ajaxurl);
$.post(ajaxurl, data).done(function(returns){
console.log(returns);
});
});
});
}(window.jQuery));
</script> <?php
}
add_action( 'admin_footer', 'cfgeo_settings_javascript');
function cfgeo_settings_callback() {
global $wpdb; // this is how you get access to the database
var_dump($_POST);
if (isset($_POST)) {
// Do the saving
$front_page_elements = array();
$updates=array();
foreach($_POST as $key=>$val){
if($key != 'cfgeo_settings')
update_option($key, esc_attr($val));
}
echo 'true';
}
else
echo 'false';
wp_die(); // this is required to terminate immediately and return a proper response
}
add_action( 'wp_ajax_cfgeo_settings', 'cfgeo_settings_callback');
?>
I find problem that everytime I want to send this simple ajax request I get 0 what is realy enoying.
Here is Console Log when I try to made some change in select option box:
Object {action: "cfgeo_settings", cf_geo_enable_ssl: "true"}
admin.php?page=cf-geoplugin-settings:1733 /wp-admin/admin-ajax.php
admin.php?page=cf-geoplugin-settings:1736 0
What's wrong in my ajax call or PHP script?
I need to mention that both codes are in the one PHP file.
You should have to follow guideline of WordPress ajax method by this admin ajax reference. Please follow this.
https://codex.wordpress.org/AJAX_in_Plugins
Here is a working example with notes included in the comments, there are a lot of don't does in your code and this example addresses those concerns in the code comments.
https://gist.github.com/topdown/23070e48bfed00640bd190edaf6662dc
I'm having an issue. When I hit submit, my form values are sent to the database. However, I would like the form to both send the value to the database and execute my script, as said in the title.
When I hit submit button, the form is sent to the database and the script remains ignored. However, if I input empty values into the input areas, the javascript is executed, and does what I want (which is to show a hidden < div >), but it's useless since the < div > is empty, as there is no output from the server.
What I want is:
submit button -> submit form -> javascript is executed > div shows up > inside div database SELECT FROM values (which are the ones added through the submitting of the form) appear.
Is this possible? I mean, to mix both PHP and JavaScript like this?
Thanks in advance.
By two ways, You can fix it easily.
By ajax--Submit your form and get response
$('form').submit(function (e){
e.preventDefault();
$.ajax({
type: "POST",
url: url, //action
data: form.serialize(), //your data that is summited
success: function (html) {
// show the div by script show response form html
}
});
});
First submit your from at action. at this page you can execute your script code .. At action file,
<?php
if(isset($_POST['name']))
{
// save data form and get response as you want.
?>
<script type='text/javascript'>
//div show script code here
</script>
<?php
}
?>
hers is the sample as I Comment above.
In javascript function you can do like this
$.post( '<?php echo get_site_url(); ?>/ajax-script/', {pickup:pickup,dropoff:dropoff,km:km}, function (data) {
$('#fare').html(data.fare);
//alert(data.fare);
fares = data.fare;
cityy = data.city;
actual_distances = data.actual_distance;
}, "json");
in this ajax call I am sending some parameters to the ajaxscript page, and on ajaxscript page, I called a web service and gets the response like this
$jsonData = file_get_contents("https://some_URL&pickup_area=$pickup_area&drop_area=$drop_area&distance=$km");
echo $jsonData;
this echo $jsonData send back the data to previous page.
and on previous page, You can see I Use data. to get the resposne.
Hope this helps !!
You need ajax! Something like this.
HTML
<form method='POST' action='foobar.php' id='myform'>
<input type='text' name='fname'>
<input type='text' name='lname'>
<input type='submit' name='btnSubmit'>
</form>
<div id='append'>
</div>
jQuery
var $myform = $('#myform'),
$thisDiv = $('#append');
$myform.on('submit', function(e){
e.preventDefault(); // prevent form from submitting
var $DATA = new FormData(this);
$.ajax({
type: 'POST',
url: this.attr('action'),
data: $DATA,
cache: false,
success: function(data){
$thisDiv.empty();
$thisDiv.append(data);
}
});
});
And in your foobar.php
<?php
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$query = "SELECT * FROM people WHERE fname='$fname' AND lname = '$lname' ";
$exec = $con->query($query);
...
while($row = mysqli_fetch_array($query){
echo $row['fname'] . " " . $row['lname'];
}
?>
That's it! Hope it helps
You can use jQuery ajax to accomplish it.
$('form').submit(function (e){
e.preventDefault();
$.ajax({
type: "POST",
url: url, //url where the form is to be submitted
data: data, //your data that is summited
success: function () {
// show the div
}
});
});
Yes, you can mix both PHP and JavaScript. I am giving you a rough solution here.
<?php
if(try to catch submit button's post value here, to see form is submitted)
{
?>
<script>
//do javascript tasks here
</script>
<?php
//do php tasks here
}
?>
Yes, This is probably the biggest use of ajax. I would use jquery $.post
$("#myForm").submit(function(e){
e.preventDefault();
var val_1 = $("#val_1").val();
var val_2 = $("#val_2").val();
var val_3 = $("#val_3").val();
var val_4 = $("#val_4").val();
$.post("mydbInsertCode.php", {val_1:val_1, val_2:val_2, val_3: val_3, val_4:val_4}, function(response){
// Form values are now available in php $_POST array in mydbInsertCode.php - put echo 'success'; after your php sql insert function in mydbInsertCode.php';
if(response=='success'){
myCheckdbFunction(val_1,val_2,val_3,val_4);
}
});
});
function myCheckdbFunction(val_1,val_2,val_3,val_4){
$.post("mydbCheckUpdated.php", {val_1:val_1, val_2:val_2, val_3: val_3, val_4:val_4}, function(response){
// put echo $val; from db SELECT in mydbSelectCode.php at end of file ';
if(response==true){
$('#myDiv').append(response);
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
I want to make a javascript function which checks the database whether the id requested by the user is available or not. My code is:
HTML:
<button type="button" onclick="chkId()">Check Availability</button><span id="chkresult"></span>
Javascript code:
function chkId()
{
$("#chkresult").html("Please wait...");
$.get("check_id.php", function(data) { $("#chkresult").html(data); });
}
The check_id.php file:
<?php
require 'connect.php';
$id_query = mysql_query("SELECT COUNT(*) AS TOTAL FROM `Table4` WHERE `Unique ID` = '$id'");
list ($total) = mysql_fetch_row($id_query);
if ($total == 0)
{
echo "Available!";
}
else if ($total > 0)
{
echo "Not Available!";
}
?>
But when the button is clicked, nothing happens. I just get a 'Please wait...' message, but as expected by the code, after 'Please wait...' it should change either to Available or to Not Available. But I only get the 'Please Wait...' message, and the result Available or Not Available is not printed on the screen. Please help me what changes do I need to make in my code.
I do not see the $id variable in your PHP script that is used by your $id_query.
Try adding that above $id_query
A few things I notice:
Your javascript is not passing the id parameter to your php backend. See the documentation for the proper syntax to pass that id param.
Your PHP is calling the mysql_query method and one of the parameters that it is passing in is the $id - but $id has not been declared. Check your PHP logs and you'll see where it is choking.
Because the PHP code is likely failing due to the unresolved variable, it is returning an error code. When JQuery receives the error code, it goes to call your ajax failure handler, but you have not declared one! Try adding a .fail(function(){}); to your get call as the docs describe - and you'll likely see the php error message show up.
EDIT: Obligatory php sql injection attack warning. Make sure to escape client input!!!
$.ajax({
type: "POST",
url: "check_id.php",
data: {
id:id; //the id requested by the user.You should set this
},
dataType: "json",
success: function(data){
$('#chkresult').html(data);
}
},
failure: function(errMsg) {
alert(errMsg);
}
});
In your php
<?php
require 'connect.php';
$id_query = mysql_query("SELECT COUNT(*) AS TOTAL FROM `Table4` WHERE `Unique ID` = '$id'");
list ($total) = mysql_fetch_row($id_query);
if ($total == 0)
{
header('Content-type: application/json');
echo CJavaScript::jsonEncode('Available');
}
else if ($total > 0)
{
header('Content-type: application/json');
echo CJavaScript::jsonEncode('Not available');
}
?>
I am trying to use ajax to add a div to display an error message. But instead of the correct error message I get null every time. The null is a result of
<?php echo json_encode($_SESSION['msg']['login-err']); ?>;
How can I fix this? Why is it showing as null?
JavaScript:
$(document).ready(function(){
$("#open").click(function(){
$("#register").fadeIn(500);
});
$("#close").click(function(){
$("#register").fadeOut(500);
});
$("#log").click(function(){
username=$("#username").val();
password=$("#password").val();
submit=$("#log").val();
$.ajax({
type: "POST",
url: "",
data: "submit="+submit+"&username="+username+"&password="+password,
success: function(html) {
if(html==true) {
}
else {
$("#error-log").remove();
var error_msg = <?php echo json_encode($_SESSION['msg']['login-err']); ?>;
$("#s-log").append('<div id="error-log" class="err welcome dismissible">'+error_msg+'</div>');
<?php unset($_SESSION['msg']['login-err']); ?>
}
}
});
return false;
});
members.php:
<?php if(!defined('INCLUDE_CHECK')) header("Location: ../index.php"); ?>
<?php
require 'connect.php';
require 'functions.php';
// Those two files can be included only if INCLUDE_CHECK is defined
session_name('Login');
// Starting the session
session_set_cookie_params(7*24*60*60);
// Making the cookie live for 1 week
session_start();
if($_SESSION['id'] && !isset($_COOKIE['FRCteam3482Remember']) && !$_SESSION['rememberMe'])
{
// If you are logged in, but you don't have the FRCteam3482Remember cookie (browser restart)
// and you have not checked the rememberMe checkbox:
$_SESSION = array();
session_destroy();
// Destroy the session
}
if(isset($_GET['logoff']))
{
$_SESSION = array();
session_destroy();
header("Location: ../../index.php");
exit;
}
if($_POST['submit']=='Login')
{
// Checking whether the Login form has been submitted
$err = array();
// Will hold our errors
if(!$_POST['username'] || !$_POST['password'])
$err[] = 'All the fields must be filled in!';
if(!count($err))
{
$_POST['username'] = mysql_real_escape_string($_POST['username']);
$_POST['password'] = mysql_real_escape_string($_POST['password']);
$_POST['rememberMe'] = (int)$_POST['rememberMe'];
// Escaping all input data
$row = mysql_fetch_assoc(mysql_query("SELECT id,usr FROM members WHERE usr='{$_POST['username']}' AND pass='".md5($_POST['password'])."'"));
if($row['usr'])
{
// If everything is OK login
$_SESSION['usr']=$row['usr'];
$_SESSION['id'] = $row['id'];
$_SESSION['rememberMe'] = $_POST['rememberMe'];
// Store some data in the session
setcookie('FRCteam3482Remember',$_POST['rememberMe']);
}
else $err[]='Wrong username and/or password!';
}
if($err) {
$_SESSION['msg']['login-err'] = implode('<br />',$err);
// Save the error messages in the session
header("Location: index.php");
}
else
header("Location: workspace/index.php");
echo 'true';
exit;
}
Normally a AJAX request makes a request to a PHP page which returns a value. It is often JSON but does not have to be. Here is an example.
$.ajax({
type: "POST",
url: "a request URL",
data:{
'POST1':var1,
'POST2':var2
}
success: function(result)
{
//Do something based on result. If result is empty. You have a problem.
}
});
Your PHP page doesn't always return a value so its hard to know whats going on. Your work-around for this is to use javascript variables wich hold echoed PHP data when your page returns empty. But this won't work in your case. Echoing PHP variables into javascript might work fine on occasion to but it is not good practise.
It won't work in your case because your javascript variables are set when the page is first loaded. At this point the variable $_SESSION['msg']['login-err'] has not been set (or might hold some irrelevant data) and this is what your javascript variables will also hold.
When you do it the way I mentioned you can also use functions like console.log(result) or alert(result) to manually look at the result of the PHP page and fix any problems.
I would suggest doing something like the following.
if($err) {
$_SESSION['msg']['login-err'] = implode('<br />',$err);
echo $_SESSION['msg']['login-err'];
}
else
echo 'success';
}
Javascript
$.ajax({
type: "POST",
url: "",
data: "submit="+submit+"&username="+username+"&password="+password,
success: function(response) {
if(response=='success') {
alert("Woo! everything went well. What happens now?");
//do some stuff
}
else {
alert("oh no, looks like we ran into some problems. Response is"+ response);
$("#error-log").remove();
var error_msg = response;
$("#s-log").append('<div id="error-log" class="err welcome dismissible">'+error_msg+'</div>');
}
}
});
This may not necessarily work exactly as you intended but its a good start for you to build on.
By going through the code , it seems that you are doing redirect first then sending the response.
There is something wrong in below code snippet
if($err) {
$_SESSION['msg']['login-err'] = implode('<br />',$err);
// Save the error messages in the session
header("Location: index.php");
}
else
header("Location: workspace/index.php");
echo 'true';
exit;
}