Send php request onclick via ajax - javascript

I know this question have been asked alot but none of the answer are related to my case ,I have a button ,onclick it should call a javascript function send it a php variable,and ajax would call a php file via post and send that vriable and the php file updates my table
so here is the onclick event first
<button class="button button6 " onclick="incrementclicks('<?php echo $id; ?>');">increment</button>
it should send a variable called $id to the javascript function
<script type="text/javascript">
function incrementclicks(id) {
$.ajax({
url: "increment.php",
data: "id=" + id,
type: "POST"
});
}
</script>
and the php file increment.php (I'm 100% sure it connects to the server just fine )
<?php
require_once 'dbconnect.php';
$db_handle = new DBController();
$id=$_POST["id"];
$q="UPDATE clicks SET linkclicks = linkclicks + 1 WHERE id = '".$id."'";
$result = mysql_query($q);
?>
it doesn't increment, I don't understand what did i do wrong here

First of all you can debug your code on the php by doing
echo $id;
exit();
My quess is that your are missing something there..

Use this method of ajax to check the issue.And if error found check in console for the issue
$.ajax({
url: "increment.php",
type: "post", //send it through post method
data: {
id:id
},
success: function (response) {
alert("success");
},
error: function (xhr) {
//Do Something to handle error
alert("some error found");
}
});
NB:Try to add type="button" to your button for not to reload
<button class="button button6 " onclick="incrementclicks(5);" type="button">increment</button>

I just want to answer this if anyone have future problems like this
The problem is I forgot to add script src at the beginning
<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
after adding this my code worked just fine :)

Related

make php script wait until ajax request is completed

I'm new to php so please bare with me. I have an ajax function that creates a post request to send data to server side php and echo it and my code should work fine. The problem is the php echo is proccessing before the create() function is ran so an error that the variables are not found is only displayed. Is there a way in php to make the echo proccess wait untill the ajax function is ran. Any help is appreciated. Thanks in advace.
function create() {
$.ajax({
url: "test.php",
type: "post",
dataType: 'json',
data: {
registration: "success",
name: "xyz",
email: "abc#gmail.com"
},
success: function(result) {
console.log(result.abc);
}
});
}
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<button onclick="create()">click me</button>
<?php
$registration = $_POST['registration'];
$name= $_POST['name'];
$email= $_POST['email'];
if ($registration == "success"){
echo json_encode(array("abc"=>'successfuly registered'));
}
?>
UPDATE: Checked if there is a POST request inorder to proccess the script but no echo.
function create() {
$.ajax({
url: "test.php", //the page containing php script
type: "post", //request type,
dataType: 'json',
data: {
registration: "success",
name: "xyz",
email: "abc#gmail.com"
},
success: function(result) {
console.log(result.abc);
}
});
}
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<button onclick="create()"> Click me</button>
<? php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$registration = $_POST['registration'];
$name= $_POST['name'];
$email= $_POST['email'];
if ($registration == "success"){
// some action goes here under php
echo json_encode(array("abc"=>'successfuly registered'));
}
}
?>
Assuming your script and button tags live in the same file as the php script the way it's shown in your question: Your code runs out of order because, as you point out yourself, you run the PHP code before your create function runs. Just because you wrote the code in order doesn't mean it will run in order.
Here's what happens, in order:
script and button tags are rendered
Your php code runs
The result of steps 1 and 2 is sent to the browser
Then somebody clicks the button
What you need to do is move the php script to a separate route that you only request upon button blick. For example test.php, assuming the code you show in your q doesn't already live in that fileā€”in that case, you'll need to put the php code in a different file.

AJAX redirect to another php file and pass javascript variable to that same php file

I am new to Ajax. I have here a function that when a button is clicked, you should be redirected to id.php and at the same time pass the value of clicked_id.
Javascript code:
function clicked(clicked_id){
window.alert("clicked");
window.alert(clicked_id);
$.post('id.php',{ID:clicked_id},
function(data){
window.alert("here");
window.location='id.php';
});
}
Inside my id.php,
<?php
$clickedID = $_GET['ID'];
echo 'here at id.php';
echo $clickedID;
?>
Now the problem is that ID in id.php cannot be identified.
Please help me. I already tried both $_POST and $_GET.
I believe that the problem here is in the passing of the variable.
there is no need for ajax if you wanna pass the id to the id.php after redirection
function clicked(clicked_id){
window.alert("clicked");
window.alert(clicked_id);
window.location='id.php?id=' + clicked_id;
}
in id.php you can get the id like this:
<?php $id = $_GET['id'];
function buttonClicked() {
$.ajax({
url: "id.php", //url for php function
type: "POST",
data: {'clicked_id':clicked_id}, // data to sent
dataType: 'json',
success: function (data)
{
}
});
}
And in your id.php file:
$_REQUEST['clicked_id']

ajax - save javascript value to php

After hours of trying to get this to work, i want to ask you :)
So i have a php Page that can display files from a server. Now I can edit
the files with a editor plugin.
Textarea is the tag where the editor gets rendered.
To save the changed text from the editor, I have a button that gets the innerHTML from the surrounding pre tag of the text with javascript.
I now want to pass that variable via ajax to a php variable on the site get.php,
so I can save it locally and send it to the server.
The problem is, that there is no reaction at all, if i click the "Save" button. I tested a lot of answers from similar ajax functions here, but none of them gave me a single reaction :/
php main
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
...
echo "<textarea><pre id='textbox'> ";
echo $ssh->exec($display);
echo "</textarea></pre>";
echo '<input type="button" value="Save File" id="butt">';
echo "<script>
var show = document.getElementById('textbox').innerHTML;
$(document).ready(function() {
$('#butt').click(function() {
$.ajax({
type: 'POST',
url: 'get.php',
data: {'variable': show},
success: function(data){
alert(data);
}
});
});
});
</script>";
...
get.php
if (isset($_POST["variable"])){
$show =$_POST["variable"];
echo $show;
}
Edit:
This is the actual working state:
echo "<textarea id='textbox'><pre> ";
echo $ssh->exec($display);
echo "</pre></textarea>";
echo '<input type="button" value="Save File" id="butt">';
echo "<script>
$(document).ready(function() {
$('#butt').click(function() {
var show = document.getElementById('textbox').value;
$.ajax({
type: 'POST',
url: 'get.php',
data: {'variable': show},
success: function(data){
alert(data);
},
});
});
});
</script>";
You have an error in the data: {'variable': show)} part. It should be: data: {variable: show}. Also you should use Firebug or Firefox developer tools for these kind of problems. A lot easier to see whats wrong.
I would suggest small changes to see if everything is running as it should.
I can see that pre tag is behind textarea closing tag - try to change it
Try putting var show = document.getElementById('textbox').innerHTML; inside of the ,,butt" function
Then I can see your problem here data: {'variable': 'show')}, - you are sending 'show' as a string - remove quotes to send it as a variable which will appear as a POST value in PHP site.
with this should work:
$.ajax({
type: 'POST',
url: 'get.php',
data: {variable: show)},
success: function (data){
alert(data);

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 :-)

undefined index error in jquery ajax request

Please check my code in the following:
PHP & HTML Code(file1.php):
<?php
$conn = //connected to db successfully.
$sql = "SELECT t1.column1 AS Column_1 FROM table1 t1";
$rs = mysqli_query($conn,$sql);
$rows= mysqli_fetch_assoc($rs);
do{
?>
<button data-id="<?php echo $rows['Column_1']; ?>" type="button" onclick="handle_item('id')">Click Me</button> <br>
<?php }while($rows = mysqli_fetch_assoc($rs)); ?>
jQuery AJAX code(file1.php):
<script type="text/javascript">
var item_id;
function handle_item(item_id) {
var c = $(this).data(item_id);
$.ajax({
url: 'handle_input.php',
type: 'POST',
data: {
'button_id': c
},
success: function (data) {
alert(data);
}
});
}
</script>
PHP Code(handle_input.php):
<?php
echo "Button with id ".$_POST['item_id]." clicked!";
?>
Now the problems is (as you might expect) the infamous error in this case, "undefined index: button_id" error. I receive it as an alert error when I click on one of the buttons. I've already read the duplicate questions on SO but unfortunately none of those I read could resolve my problem. I appreciate your guiding me with this.
Besides, as you see from my codes, I'm fetching several button from database and while displaying, I assign each one a data-id and use that data-id in ajax to use in 'handle_input.php' and I want to receive each button id which I've clicked on. Thanks in advance.
UPDATE:
It's been a while since I've asked this question but I've been curios about something in my question:
Why doesn't the array mode(data: {"button_id":c}) work for me in the $.ajax function(which leads to undefined index error for the $_POST variable) whereas the string mode(data: "usg_id="+c) does?
You're sending:
button_id:..
but you're using, also with a missing '
$_POST['item_id]
change to:
$_POST["button_id"]
UPDATE
Add this as first parameter:
onclick="handle_item(this, 'id')"
Then, changehandle_item function as this:
function handle_item(obj,item_id) {
var c = $(obj).data(item_id);
<script type="text/javascript">
var item_id;
function handle_item(item_id) {
var c = $(this).data(item_id);
$.ajax({
url: 'handle_input.php',
type: 'POST',
data:"item_id="+c,
success: function (data) {
alert(data);
}
});
}
</script>
There is no button_id defined in you function hence the error.
Also in handle_input you are fetching item_id

Categories