Can not pass variable by ajax to other php file - javascript

I want to pass a variable from one PHP file to another, for that, I am trying to use ajax. Now, in my 'index.php' file, I have a button. When that button is clicked, I want to pass that button's id to another PHP file which is 'show_schedule.php'.
Here is my index.php file's ajax code:
$(document).on('click', '.show', function(){
var schedule_id = $(this).attr("id");
$.ajax({
url:"show_schedule.php",
method:"POST",
data:{schedule_id:schedule_id},
dataType:"json",
success:function(data)
{
window.location.href = 'show_schedule.php';
}
});
});
Here is my 'show_schedule.php' file:
<?php
session_start();
if(isset($_POST["schedule_id"])){
$s_id = $_POST['schedule_id'];
echo $s_id;
}
?>
data is index.php is fetched & displayed by 'fetch.php', in which, that button is set like this:
'<button type="button" name="show" id="'.$row["s_id"].'" class="btn btn-primary btn-sm show">Show</button>';
When I click on this button, I am redirected to 'show_schedule.php', but the variable value is not passed, i.e. nothing is printed on that page. Can anyone tell me where I am making mistake? Any help is appriciated.

You could just do the following and change the php to take the GET param i.e.
$(document).on('click', '.show', function(){
var schedule_id = $(this).attr("id");
window.location.href = 'show_schedule.php?schedule_id='+schedule_id;
});
});
If it HAS to be a POST then a few solutions to be found # pass post data with window.location.href

I have send data using jQuery ajax post request to getval.php file and data will be send successfully.
ajax.php
!DOCTYPE html>
<html>
<head>
<title>ajax request</title>
<!-- jQuery cdn -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<button id="send-data">send data</button>
<div class="data"></div>
</body>
</html>
<script type="text/javascript">
$(document).ready(function () {
$('#send-data').click(function () {
let val = "test"; // send val variable data
$.post("getval.php", { value: val }, function (data, status) { //send data using post request
if (status == "success") {
$('#send-data').remove();
$('.data').append(data);
}
});
});
});
</script>
getval.php
<?php
if (isset($_POST['value'])) {
$data = $_POST['value'];
echo "<br>The data is : ".$data;
}
?>
OUTPUT :-
The data is : test

Related

Working in Local system but not when uploaded in server

I created a simple form, onSubmit it takes the values to js page(AJAX CALL) then send to add.php page again returns the value to html page.
This code is working fine on my local system but when i test it in server AJAX call is not working.Even i just tested as on submit(click) alert from add.js(AJAX) but not working and works good in local(XAMP)
var btn = document.getElementById("sub");
btn.addEventListener("click", function() {
//alert('came');
var data=$("#myForm :input").serializeArray();
$.post($("#myForm").attr("action"),data,function(info){
$("#result").html(info);
});
});
$("#myForm").submit(function() {
return false;
});
<!DOCTYPE html>
<html>
<head>
<title>
Ajax call
</title>
</head>
<body>
<form id="myForm" action="add.php" method="post">
<input type="text" name="uname">
<input type="text" name="age">
<button id="sub">submit</button>
</form>
<span id="result"></span>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="add.js"></script>
</body>
</html>
Here is my add.php , which echo the result that will be displayed in my html result div tag `
<?php
$name=$_POST['uname'];
$age=$_POST['age'];
echo $name;
Is there anything to change while uploading in server.Whats wrong in my code.
Thanks in advance.
This is the object you are sending to the server, you can see that it has not the structure that the server side 'add.php' is expecting, so there is no $_POST['uname'] variable. You may use a var_dump($_POST) to see the structure you are receiving or use $("#myForm").serialize() that I've used a lot and worked fin to me.
var btn=document.getElementById("sub");
btn.addEventListener("click",function(){
alert('came');
var data=$("#myForm :input").serializeArray();
$.post($("#myForm").attr("action"),data,function(info){
$("#result").html(info);
$('#myForm')[0].reset();*/
//please have a look in your add.js:9:26
});
});
$("#myForm").submit(function(){
return false;
});
Could you follow ajax in this method, Surely it will works for you.
<button type="button" onclick="submit()" class="input-group-addon addbtn">Submit</button>
function submit(){
var data = $("#myForm").serialize();
$.ajax({
url: 'your url',
type: "post",
data: {'formSerialize':data, '_token': $('meta[name="_token"]').attr('content')},
success: function(data){
if(data.success==1){
alert('success');
}else if(data.error==1){
alert('error');
}
}
});
}
In your controller you can get the value like this
parse_str($data['formSerialize'],$input);
In $input You can easily access all the field value.
Problems: I'm not 100% sure what's causing your problem. But on my end I found the problem to be browser related since it worked on Chrome but not on FireFox.
One scenario would that FireFox didn't recognize your:
$("#myForm").submit(function() {
return false;
});
It does happen that FireFox will do so if you don't abide by its standards. I did explain this in my answer about event.preventDefault();
I also completely changed your add.js as I've found some of your code unnecessary and that it could be combined into a cleaner function. Since you're already using jQuery might as well stick to it and not use DOM.
FORM:
<!DOCTYPE html>
<html>
<head>
<title>
Ajax call
</title>
</head>
<body>
<form id="myForm">
<input type="text" name="uname">
<input type="text" name="age">
<button type="submit">Submit</button>
</form>
<span id="result"></span>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="add.js"></script>
</body>
</html>
ADD.JS
//you need to add "event" as a parameter to the function since Firefox
//will not recognize event.preventDefault(); if its missing
$( "#myForm" ).on( "submit", function( event ) {
event.preventDefault(); //this will prevent the form from submitting
var form_data = $("#myForm").serialize();
$.ajax({
method: "POST",
url: "add.php",
data: {form_data: form_data},
success: function (info) {
$("#result").html(info);
}
});
});
ADD.PHP
<?php
$form_data = $_POST['form_data'];
$params = array();
parse_str($form_data, $params);
$name = $params['uname'];
$age = $params['age'];
echo $name;

how to update a value in database using jquery when a link is clicked in php

I want to increment count field in database when a link is clicked in php file.
So, I've added the following jquery part to my .php file. But still, it doesn't work. Please help!
<body>
click here
<script>
$(function ()
{
$('#click').click(function()
{
var request = $.ajax(
{
type: "POST",
url: "code.php"
});
});
}
</script>
</body>
code.php:
<?php
$conn=mysqli_connect("localhost","root","","sample");
mysqli_query($conn,"UPDATE e set count=(count+1) WHERE sid='1'");
mysqli_close($connection);
?>
You made a several mistakes in your code.
Update
You can send your SID input type text from ajax with data and you can get the value in your php file with the $sid = $_POST['sid'].
<body>
click here
<input type="text" value="" name="sid" id="sid">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(e){
$('#click').click(function(event)
{
var sidvalue = $("#sid").val(); /*from here you get value of your sid input box*/
event.preventDefault();
var request = $.ajax(
{
type: "POST",
url: "code.php",
data: 'sid='+sidvalue ,
success: function() {
window.location.href = 'https://www.google.com/';
}
});
});
});
</script>
After the ajax success response you can make redirect to your desire location.
Code.php
<?php
$conn=mysqli_connect("localhost","root","","sample");
$sid = $_POST['sid']; // use this variable at anywhere you want.
mysqli_query($conn,"UPDATE e set count=(count+1) WHERE sid='1'");
mysqli_close($conn);
?>
in code.php in mysqli_close you should use $conn not $connection.
Go with this code. It might help you. I have just tested all the things in localhost. This is working perfect.
use preventDefault() when click event is called.check jquery :
<body>
click here
<script>
$(function ()
{
$('#click').click(function(e)
{
e.preventDefault();
var request = $.ajax(
{
type: "POST",
url: "code.php"
});
});
}
</script>
</body>
Redirect your link on ajax success. Like this -
<body>
click here
<script>
$(function ()
{
$('#click').click(function()
{
var request = $.ajax(
{
type: "POST",
url: "code.php",
success: function(response){
window.location="http://www.google.com";
}
});
});
}
</script>

Enter ID in html form and load related data from MySQL database in same page

I have a form with an input field for a userID. Based on the entered UID I want to load data on the same page related to that userID when the user clicks btnLoad. The data is stored in a MySQL database. I tried several approaches, but I can't manage to make it work. The problem is not fetching the data from the database, but getting the value from the input field into my php script to use in my statement/query.
What I did so far:
I have a form with input field txtTest and a button btnLoad to trigger an ajax call that launches the php script and pass the value of txtTest.
I have a div on the same page in which the result of the php script will be echoed.
When I click the button, nothing happens...
Test.html
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
<script>
//AJAX CALL
function fireAjax(){
$.ajax({
url:"testpassvariable.php",
type:"POST",
data:{userID:$("#txtTest").val(),},
success: function (response){
$('#testDiv').html(response);
}
});
}
</script>
</head>
<body>
<form name="testForm" id="testForm" action="" method="post" enctype="application/x-www-form-urlencoded">
<input type="text" name="txtTest" id="txtTest"/>
<input type="button" id="btnLoad" name="btnLoad" onclick="fireAjax();"
<input type="submit" name="SubmitButton" id="SubmitButton" value="TEST"/>
</form>
<div id="testDiv" name="testDiv">
</div>
</body>
The submit button is to insert updated data into the DB. I know I have to add the "action". But I leave it out at this point to focus on my current problem.
testpassvariable.php
<?php
$player = $_POST['userID'];
echo $player;
?>
For the purpose of this script (testing if I can pass a value to php and return it in the current page), I left all script related to fetching data from the DB out.
As the documentation says 'A page can't be manipulated safely until the document is ready.' Try this:
<script>
$(document).ready(function(){
//AJAX CALL
function fireAjax(){
$.ajax({
url:"testpassvariable.php",
type:"POST",
data:{userID:$("#txtTest").val(),},
success: function (response){
$('#testDiv').html(response);
}
});
}
});
</script>
You need to correct two things:
1) Need to add $(document).ready().
When you include jQuery in your page, it automatically traverses through all HTML elements (forms, form elements, images, etc...) and binds them.
So that we can fire any event of them further.
If you do not include $(document).ready(), this traversing will not be done, thus no events will be fired.
Corrected Code:
<script>
$(document).ready(function(){
//AJAX CALL
function fireAjax(){
$.ajax({
url:"testpassvariable.php",
type:"POST",
data:{userID:$("#txtTest").val(),},
success: function (response){
$('#testDiv').html(response);
}
});
}
});
</script>
$(document).ready() can also be written as:
$(function(){
// Your code
});
2) The button's HTML is improper:
Change:
<input type="button" id="btnLoad" name="btnLoad" onclick="fireAjax();"
To:
<input type="button" id="btnLoad" name="btnLoad" onclick="fireAjax();"/>
$.ajax({
url: "testpassvariable.php",
type: "POST",
data: {
userID: $("#txtTest").val(),
},
dataType: text, //<-add
success: function (response) {
$('#testDiv').html(response);
}
});
add dataType:text, you should be ok.
You need to specify the response from the php page since you are returning a string you should expect a string. Adding dataType: text tells ajax that you are expecting text response from php
This is very basic but should see you through.
Change
<input type="button" id="btnLoad" name="btnLoad" onclick="fireAjax();"/>
Change AJAX to pass JSON Array.
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "action.php",
data: data,
....
// action.php
header('Content-type: application/json; charset=utf-8');
echo json_encode(array(
'a' => $b[5]
));
//Connect to DB
$db = mysql_connect("localhst","user","pass") or die("Database Error");
mysql_select_db("db_name",$db);
//Get ID from request
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
//Check id is valid
if($id > 0)
{
//Query the DB
$resource = mysql_query("SELECT * FROM table WHERE id = " . $id);
if($resource === false)
{
die("Database Error");
}
if(mysql_num_rows($resource) == 0)
{
die("No User Exists");
}
$user = mysql_fetch_assoc($resource);
echo "Hello User, your number is" . $user['number'];
}
try this:- for more info go here
$(document).ready(function(){
$("#btnLoad").click(function(){
$.post({"testpassvariable.php",{{'userID':$("#txtTest").val()},function(response){
$('#testDiv').html(response);
}
});
});
});
and i think that the error is here:-(you wrote it like this)
data:{userID:$("#txtTest").val(),}
but it should be like this:-
data:{userID:$("#txtTest").val()}
happy coding :-)

Php mysql undefined index error used jquery for traferring data from one page to another

This is my first project where I used Jquery.
There are two pages 1. listofleaders.php 2. leadersprofile.php
On First Page i.e. listofleaders.php
I have a input text box, where user enters leaders name and I used jQuery code to transfer textbox values to leaderprofile.php page
<html>
<head>
<script>
function ls()
{
var leaderdetails = "leaderprofile.php?lname="+$("#gopal").val();
$.get(leaderdetails, function( data ) {
//alert(leaderdetails);
location.href = "leaderprofile.php";
});
}
</script>
</head>
<body>
<input type="text" id="gopal" name="t" placeholder="Start Typing" size="50" />
<button onclick="ls();" type="button">Go!</button><br><br>
</body>
</html>
On Second Page leadersprofile.php I have written this,
<?php
include "admin/includes/dbconfig.php";
$lname = $_GET['lname'];
echo $lname;
?>
But on second page i.e. leaderprofile.php it is showing me error
Undefined index : lname
Am I Correct to this approach ?
Where I am Wrong ?
Hope you Understand.
So I am having a guess here at what you are trying to achieve based on your problem description.
If you want to send a <input> value to another page, you better use a classic POST request (without the need of evolving jQuery):
<form method="post" action="leadersprofile.php">
<input type="text" name="lname"/>
<button type="submit">Send</button>
</form>
And in leadersprofile.php:
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['lname'])) {
$lname = $_POST['lname'];
var_dump($lname); // outputs whatever the user input was
}
Now if you want to send the data to leadersprofile.php without reloading the page, you are looking for an Ajax request (XmlHttpRequest).
jQuery(function($) {
$('form').on('submit', function(e) {
e.preventDefault(); // prevents default behavior that is submitting the form
$.ajax({
method: 'post', // can be also 'get'
url: 'leadersprofile.php',
data: {lname: $('input').val() },
success: function(html) {
$('div').html(html); // place whataver was printed in leadesrprofile.php into a div
},
error: function(r) { // fire if HTTP status code != 200
console.log(r);
}
});
});
});
You seem to be using JQuery correctly. The Javascript to extract the value and the send the GET request should be working.
Your misunderstanding lies in how you check if the PHP file has received the request. This redirect
location.href = "leaderprofile.php";
Will not provide you any information about the GET request that you just made. Instead you can try:
location.href = "leaderprofile.php?lname=" + $("#gopal").val()
To verify that your PHP and Javascript is performing as expected. If you see the values that you expect then I believe you have confirmed two things:
successfully extracted the correct value from the textbox
GET request is succeeding, and the success callback is being invoked
I understand your question.Try the following codes.
listofleaders.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<form>
<table>
<tr>
<td>Name:</td>
<td><input type="text" id="name"></td>
</tr>
<tr>
<td></td>
<td><button id="submit">Submit</button></td>
</tr>
</table>
</form>
<script src = "jquery.js"></script>
<script src = "leader.js"></script>
</body>
</html>
When submit button is click, leader.js file will get the value of text box.
leader.js
$(document).ready(function() {
$('#submit').on('click', function(){
var name = $('#name').val();
$.ajax({
url:'leaderprofile.php',
type:'POST',
data:{'name':name},
success:function(data){
}
});
});
});
Now, this leader.js file will send the name key to liderprofile.php.
After that php file witt return the data(name) to js file..and the js file will alert name.
leaderprofile.php
<?php
$name = $_POST['name'];
echo $name;

Random string picker only execute once per page load

When you press the link text it is supposed to give you an random string from a file, which it does on first click. But second click nothing happens, I need to refresh page before execute it again..
Code:
function randomName() {
$names = file('layout/sub/names.txt', FILE_IGNORE_NEW_LINES);
$array = array_rand($names);
return $names[array_rand($names)];
}
<div class="randomName">
</div>
<button class="aardvark">Pick random name</button>
<script>
$(document).on('click','.aardvark', function(e){
$('.randomName').html('<?php echo randomName(); ?>');
});
</script>
The issue is the age old PHP is server side and and javascript(jQuery) is client side problem, you cant call/run PHP from javascript as its already happened.
You will need to use AJAX to re-request a new name. Here is a copy and paste example, your welcome ;p
<?php
//is ajax
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
//is get name
if(isset($_POST['get_name'])){
$names = file('names.txt', FILE_IGNORE_NEW_LINES);
exit(json_encode(array('resp' => $names[array_rand($names)])));
}
}
?>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title></title>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
//get_name function
$.fn.get_name = function(){
var elm = $(this);
var ajax = $.ajax({
url: "./",
type: "POST",
data: {'get_name':true},
dataType: "json"
});
ajax.done(function(data){
elm.html(data.resp);
});
ajax.fail(function(xhr, status, error){
elm.html("AJAX failed:" + xhr.responseText);
});
return this;
};
//do get_name on page load
$('#randomName').get_name();
//do get_name on button click
$('#aardvark').on('click', function(){
$('#randomName').get_name();
});
});
</script>
</head>
<body>
<div id="randomName"></div>
<button id="aardvark">Pick random name</button>
</body>
</html>

Categories