Passing variables from Javascript to PHP using AJAX and Jquery - javascript

I am trying to write a simple web page to send data from an html page to a php script and receive some data back from the php. I am attempting to do this with ajax, but the php script never even runs.
This is the HTML.
<script>
$(document).ready(function(){
$('.button').click(function(){
alert("hi");
var clickBtnValue = "hi";
var ajaxurl = 'add.php',
data = {'action': clickBtnValue};
$.post(ajaxurl, data, function (response) {
// Response div goes here.
alert("action performed successfully");
});
});
});
</script>
This is the PHP.
<?php
if (isset($_POST['action'])) {
switch ($_POST['action']) {
case 'insert':
insert();
break;
case 'select':
select();
break;
}
}
function select() {
echo "The select function is called.";
exit;
}
function insert() {
echo "The insert function is called.";
exit;
}
?>
<script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.1.8/semantic.js"></script>
This is included as well. I really can't figure out why it doesn't run the PHP script. Am I attempting to use out of date commands?
EDIT : Added the button HTML code
<div class="ui one column stackable center aligned page grid">
<div class="column twelve wide">
<form>
<button id = "submit_query" type = "button" class="ui green button">Submit</button>
</form>
</div>
</div>

the reason php script is not executing is, it fails to satisfy switch statement
because you are passing value "hi" instead of "insert" or "select"
var clickBtnValue = "insert";//here value is hi instead of insert or select
var ajaxurl = 'add.php',
data = {'action': clickBtnValue};
$.post(ajaxurl, data, function (response) {
// Response div goes here.
alert("action performed successfully");
});
});

Your Html form
<div class="ui one column stackable center aligned page grid">
<div class="column twelve wide">
<form>
<input type="hidden" name="action" value "insert"> <!-- either insert or select -->
<button id = "submit_query" type = "button" class="ui green button">Submit</button>
</form>
</div>
</div>
In your Js edit it accordingly
$("form").submit(function(event){
// stop the form from submitting
event.preventDefault();
var $form = $(this);
// Get input from all the fields
var $inputs = $form.find("input, select, button, textarea");
// Serialize the data in the form
var serializedData = $form.serialize();
$.post('/add.php', serializedData, function(response) {
// Log the response to the console
console.log("Response: "+response);
});
});
With this you can pass the data to the add.php
Next you can fetch it using
if (isset($_POST['action'])) {
switch ($_POST['action']) {
case 'insert':
insert();
break;
case 'select':
select();
break;
}
}
function select() {
echo "The select function is called.";
}
function insert() {
echo "The insert function is called.";
}

Related

Change the color of a button using Jquery Ajax (Color received from external PHP file)

This is my HTML code
<form class="addtowatchlistform" action="logo/insertwatchlist.php" method="POST">
<input type="hidden" name="tmdb_id" value="'.$result[$x]["tmdb_id"].'"/>
<button id="addtowatchlistbutton" type="submit" name="tmdb_id" value="'.$result[$x]["tmdb_id"].'" data-tooltip="'.$addremove.' TO YOUR WATCHLIST" class="material-icons" style="color:'.$watchlisticoncolor.'">add_box</button>
</form>
// Same form as above
<form class="addtowatchlistform" action="logo/insertwatchlist.php" method="POST">
<input type="hidden" name="tmdb_id" value="'.$result[$x]["tmdb_id"].'"/>
<button id="addtowatchlistbutton" type="submit" name="tmdb_id" value="'.$result[$x]["tmdb_id"].'" data-tooltip="'.$addremove.' TO YOUR WATCHLIST" class="material-icons" style="color:'.$watchlisticoncolor.'">add_box</button>
</form>
Jquery Code:
<script>
$(".addtowatchlistform").submit(function(e) {
var data = $(this).serialize();
var url = $(this).attr("action");
$.post(url, data, function() {
try {
data = JSON.parse(data);
$("button#addtowatchlistbutton").css('color',data.watchlisticoncolor);
} catch (e) {
console.log("json encoding failed");
return false;
}
});
return false;
});
</script>
PHP file insertwatchlist.php file
$response = new \stdClass();
$response->watchlisticoncolor = "red";
die(json_encode($response));
Output of PHP file insertwatchlist.php file
{"watchlisticoncolor":"red"}
Expected Result:
1.)When someone clicks on add_box button, it submits the form without reloading the page (This one works fine)
2.) insertwatchlist.php sends this code: {"watchlisticoncolor":"red"} and, the Jquery code place them in place of: $watchlisticoncolor variable, in the real time without reloading the page. (This one do not work),
Console tab do not show anything. Here is the screenshot of network tab, when someone clicks on the button http://prntscr.com/fxwt16
Please use background-color instead of color. color property will be used when you want to change color of fonts.
FROM
$("button#addtowatchlistbutton").css('color',data.watchlisticoncolor);
TO
$("button#addtowatchlistbutton").css('background-color',data.watchlisticoncolor);
also add data in your ajax function.
$.post(url, data, function(data) {
Let me know if it not works.
$(".addtowatchlistform").submit(function(e) {
e.preventDefault();
var data = $(this).serialize();
var url = $(this).attr("action");
$.ajax({
url: url,
type: 'post',
dataType: 'json',
beforeSend: function() {
$('#add_to_wishlist').css('color','red');
},
success: function(data) {
}
});
});
$('#add_to_wishlist2').click(function(e){
e.preventDefault();
$(this).css('background-color','red');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="add_to_wishlist" style="color:yellow;">Change Color</button>
<button id="add_to_wishlist2">Change Background Color</button>
Try this you have to catch data return from your ajax request in function params
<script>
$(".addtowatchlistform").submit(function(e) {
var data = $(this).serialize();
var url = $(this).attr("action");
var form = $(this); // Add this line
$.post(url, data, function(data) { //<---------add data here
try {
data = JSON.parse(data);
$(form).children("button").css('color',data.watchlisticoncolor); //Update this line
} catch (e) {
console.log("json encoding failed");
return false;
}
});
return false;
});
</script>
Updated:
On further checking I found its not the css proper. Its your jquery post function problem.
You are missing data in the function. Use below; Let me know if it fix your issue.
$.post(url, data, function(data) {
try {
data = JSON.parse(data);
$("button#addtowatchlistbutton").css('color',data.watchlisticoncolor);
} catch (e) {
console.log("json encoding failed");
return false;
}
color property used for text color.
Use background-color instead of color
For Background Color
$("button#addtowatchlistbutton").css('background-color',data.watchlisticoncolor);
For Text Color
$("button#addtowatchlistbutton").css('color',data.watchlisticoncolor);

How do I execute a php switch case with ajax onclick and have it print the result in an H tag?

I have a page called beslutning.php with a random generator first followed by a switch case.
That page is included in the index file like so:
<h1 class="cover-heading">Vores beslutning: <?php include "beslutning.php" ?></h1>
On a page load it runs the script, match a case and echoes out the result as it's intended.
Here's what I need
A button on the index page which when clicked requests the beslutning.php to be run again so I get a new result.
All my searches on phrases such as execute php script with ajax, run a php script with ajax onclick and a bunch of other alternatives has lead me to no result.
I have tried to fiddle with blocks of codes like the one below but to no luck.
<script>
$(document).ready(function(){
$("#NyBeslutning").click(function() {
$.ajax({
type: "POST",
url: "beslutning.php", //Your required php page
data: "$beslutning", //pass your required data here
success: function(response){
$('$beslutning').html(response);
}
});
return false;
});
</script>
<a id="NyBeslutning" class="btn btn-lg btn-default" type="button" onClick="$beslutning()">Ny beslutning</a>
Here's how my beslutning.php looks like:
<?php
$beslutning = mt_rand(0, 1000);
switch($beslutning)
{
case 1:
echo "something";
break;
case 2:
echo "something";
break;
?>
Someone who can help?
Explain it to me like I'm a baby :)
Thanks in advance.
You're close, but you have some big problems with your jQuery code. Try to read up on documentation for these things before using them!
You aren't sending any data, so don't need to POST and can just do a simple GET request. In your success function you were referring to $('$beslutning') which isn't anything. Instead you want to refer to your H1 element. And, you'd forgotten closing braces around some code.
On the HTML side, you don't need an onclick attribute, since you're already declaring the click listener in the script. Give this a try, and if it doesn't work, check your browser's error console.
<script>
$(document).ready(function(){
$("#NyBeslutning").click(function() {
$.get("beslutning.php", function(response) {
$('h1.cover-heading').html(response);
});
});
});
</script>
<h1 class="cover-heading">Vores beslutning: <?php include "beslutning.php" ?></h1>
<button id="NyBeslutning" class="btn btn-lg btn-default">Ny beslutning</button>
You must run onto virtual server (laragon etc.).
localhost/index.php <
PHP as select
file: index.php
<form class="selected">
<select name="category" id="categories">
<option value="">vyberte si...</option>
<option value="cuba">Rum</option>
<option value="cola">Cola</option>
<option value="saris">Beer</option>
<option value="moto">Oil</option>
<option value="barique">Wine</option>
</select>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="app.js"></script>
PHP Switch Case
file: ajax.php
<?php
$category = $_POST['category'];
switch ($category) {
case "cuba":
print "You must read Dickens.";
break;
case "cola":
print "Don't touche me!";
break;
case "moto":
print "You will not move without me.";
break;
default:
print "Great, relax it.";
}
?>
jQuery AJAX:
file: app.js
(function($){
var comment = $('<div/>', { id: 'comment' }); // create new element
var categories = $('#categories');
comment.appendTo( $('.selected') );
categories.change( function() {
var req = $.ajax({
url: 'ajax.php',
type: 'POST',
data: categories.serialize()
});
req.done( function(data){
//console.log( data);
comment.text( data );
})
});
})(jQuery);
You can just pass a parameter when you click something in the index.php
<button onmousedown=someFunction()>Click ME</button>
<script>
someFunction(){
set href value here based on your condition example one,two, three
window.location = localhost/main.php?switchVariable = one;
}
</script>
in main.php
<h1 class="cover-heading">Vores beslutning: <?php include "beslutning.php" </h1>
write
in beslutning.php file write this
<?php
$beslutning= $_GET['switchVariable '];
switch($beslutning)
{
case one:
echo something;
break;
case two:
echo something;
break;
?>

Use js variable for html form that will be used in php query

I have index.php page where data is pulled from database and displayed as simple table (each row can be selected with my js script).
I have js script which does all selection and stores ID number from the table into the js variable.
$(function() {
/* Get all rows from table but not the first one
* that includes headers. */
var rows = $('tr').not(':first');
/* Create 'click' event handler for rows */
rows.on('click', function(e) {
/* Get current row */
var row = $(this);
/* highlights the row*/
rows.removeClass('highlight');
row.addClass('highlight');
/*outputs the ID of the selected row to rowID variable*/
var currentRow=$(this).closest("tr");
var col1=currentRow.find("td:eq(0)").html();
var rowID=col1;
});
});
I have another dbUpdate.php script which has html form and php query.
if( !$_POST["e1"] ){
$e1Error = "Please enter value <br>";
} else {
$e1 = validateFormData ( $_POST["e1"] );
}
if( !$_POST["rowID"] ){
$rowID = validateFormData ( $_POST["rowID"] );
}
// check variable has data
if( $e1 && $rowID ) {
$query = "UPDATE athletes SET e1 = ($e1) WHERE id = ($rowID) ";
and here is the html form
<form action="<?php echo htmlspecialchars( $_SERVER["PHP_SELF"] ); ?>" method="post">
<small class="text-danger">* <?php echo $e1Error; ?></small>
<input type="text" placeholder="e1" name="e1"><br><br>
<input type="hidden" id="rowID1" name="rowID" value=""/>
My aim is to get that ID number from js variable rowID and store it in my dbUpdate.php form (name="rowID") when i select one of the rows in my html table (shown in the picture).
Here's an ajax example (using jQuery syntax, since that's what it looks like you're using):
rows.on('click', function(e) {
$.ajax({
url: '/dbUpdate.php',
type: 'POST',
data: { rowID: $(rowID).val() },
cache: true,
success: function (data) {
alert('Woot!');
}
, error: function (xhr, ajaxOptions, thrownError) { alert(thrownError); }
});
});
Now, obviously, that's going to just pull the return back into your success function. If you're trying to have your dbUpdate.php page return html to the client, that's a different story. What are you trying to do, exactly?

PHP validation for Javascript

I have a new problem. My whole website is written in PHP as well as all validations. Is there a way to do validations in php and then execute javascript like the example bellow?
if (#$_POST['submit']) {
if ($txt == "") {
$err = "No comment";
}
else {
echo "<script type='text/javascript'>
function myFunction() {
var txt' = '$txt';
var dataString = 'txt=' + txt;
$.ajax({
type: 'POST',
url: 'ajaxjs.php',
data: dataString,
cache: false,
success: function(php) {
alert(php);
}
});
}
</script>";
}
}
<div id="text">
<form action="" method='POST'>
<textarea maxlength="2000"></textarea>
<input type='button' onclick="myFunction()" name='submit' value='post' />
</form>
</div>
This doesn't work. So I'm wondering how should I do it?
I guess forms don't work with javascript, but how do I do it without a form?
You don't need to use php at all. You can post your textarea data like in the below example.
HTML
<div id="text">
<textarea id="txtArea" maxlength="2000"></textarea>
<button id="btnSubmit" name='submit'>post</button>
</div>
Javascript/jQuery
$("#btnSubmit").on('click',function(e) {
e.preventDefault();
var txtValue = $("#txtArea").val();
if(txtValue.length==0) {
alert("You have not entered any comments");
} else {
$.ajax({
type: 'POST',
url: 'ajaxjs.php',
data: {txt:txtValue},
cache: false
})
.done(function() {
alert( "success" );
})
.fail(function() {
alert( "error" );
});
}
});
The solutions is:
1. add function for submit event.
2. call ajax with form fields values as data.
3. do vildation inside php called with ajax request and return status code (valid/not valid)
4. analyse code in js and output error/success message.
First of all: Your code has a couple of errors.
You are asking if $txt == "" whilst $txt was not visibly set.
Your text area has no name
Your if doesn't ask if empty($_POST["submit"])
Second of all: You mentioned that you want the code to be executed on submit of the form. Therefore you can simple do this:
<form onsubmit="formSubmit();">
...
</form>
<script>
function formSubmit()
{
if(...)
{
return true; // Valid inputs, submit.
}
return false; // Invalid inputs, don't submit.
}
</script>
The return false is important because if it would miss, the form would be submitted as usual.

Send a hidden ID input field with AJAX

With this AJAX script, I'm trying to send the content of contentText and contentID.
Just sending contentTEXT works, but I want to send the ID as well, so I can comment on the original post.
But it doesn't work!
myData looks like this when it semi works:
> var myData = '?content_txt='+$("#contentText").val(),
> '&content_id='+$("#contentId").val(); //build a post data structure
But i want it to be something like this, i think
<script type="text/javascript"> $(document).ready(function() {
//##### send add record Ajax request to response.php ######### $("#FormSubmit").click(function (e) { e.preventDefault(); if($("#contentText").val()==='') {
alert("Please enter some text!");
return false; }
$("#FormSubmit").hide(); //hide submit button $("#LoadingImage").show(); //show loading image
var myData = '?content_txt='+$("#contentText").val(), '&content_id='+$("#contentId").val(); //build a post data structure
jQuery.ajax({ type: "POST", // HTTP method POST or GET url: "response.php", //Where to make Ajax calls contentType: "application/x-www-form-urlencoded;charset=UTF-8", dataType:"text", // Data type, HTML, json etc. data:myData, //Form variables success:function(response){
$("#responds").append(response);
$("#contentText").val(''); //empty text field on successful
$("#FormSubmit").show(); //show submit button
$("#LoadingImage").hide(); //hide loading image
}, error:function (xhr, ajaxOptions, thrownError){
$("#FormSubmit").show(); //show submit button
$("#LoadingImage").hide(); //hide loading image
alert(thrownError); } }); });
//##### Send delete Ajax request to response.php ######### $("body").on("click", "#responds .del_button", function(e) { e.preventDefault(); var clickedID = this.id.split('-'); //Split ID string (Split works as PHP explode) var DbNumberID = clickedID[1]; //and get number from array var myData = 'recordToDelete='+ DbNumberID; //build a post data structure
$('#item_'+DbNumberID).addClass( "sel" ); //change background of this element by adding class $(this).hide(); //hide currently clicked delete button
jQuery.ajax({ type: "POST", // HTTP method POST or GET url: "response.php", //Where to make Ajax calls dataType:"text", // Data type, HTML, json etc. data:myData, //Form variables success:function(response){
//on success, hide element user wants to delete.
$('#item_'+DbNumberID).fadeOut(); }, error:function (xhr, ajaxOptions, thrownError){
//On error, we alert user
alert(thrownError); } }); });
}); </script>
My form I'm trying to use
<form class="form-horizontal" accept-charset="utf-8">
<fieldset>
<legend><?php echo WORDING_ADD_A_COMMENT; ?></legend>
<!-- Textarea -->
<div class="control-group">
<div class="controls">
<textarea name="content_txt" id="contentText" cols="45" rows="5" placeholder="<?php echo WORDING_COMMENT_PLACEHOLDER; ?>"></textarea>
<input type="hidden" name="content_id" id="contentId" value="<?php echo $_GET['topic_id']; ?>"/>
</div>
</div>
<!-- Button -->
<div class="control-group">
<label class="control-label" for="singlebutton"></label>
<div class="controls">
<button id="FormSubmit" class="btn btn-primary"><?php echo WORDING_BUTTON_COMMENT_BOX; ?></button>
<img src="images/loading.gif" id="LoadingImage" style="display:none" />
</div>
</div>
</fieldset>
</form>
var variable = {
'content_txt': $("#contentText").val(),
'content_id': $("#contentId").val()
};
try to use
var myData = '?content_txt='+$("#contentText").val()+'&content_id='+$("#contentId").val();
You only use ? and & when you manually build a query string and in that case you would need to encode your values as well.
When you send the data as a parameter, the easiest solution is to generate an object. That will be encoded automatically by jQuery:
//build a post data structure
var myData = { 'content_txt': $("#contentText").val(),
'content_id': $("#contentId").val() };
As you are using a form, you can also serialize the form:
var myData = $('.form-horizontal').serialize();
data:'content_id='+ $("#contentId").val()+ '&content_txt='+ $("#contentText").val() ,

Categories

Resources