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.
Related
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);
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 :)
I want passing 2 parameters to PHP page via AJAX and load the response, but this code is not working.
JavaScript:
$(".show_category").click(function(){
var category_id = $(this).attr('data-category');
$.ajax({
url: "conx.php",
method: "POST",
data: {
action: "sort_category",
category_id: category_id
},
success: function(data) {
$("#con").load("conx.php");
}
});
});
PHP:
<?php
echo "1".$_POST["action"]."<br/>";
?>
You issue is here:
success: function(data) {
$("#con").load("conx.php");
}
At this point, you have already posted the data and received the HTML response. There is no need to make another HTTML request by calling .load, and doing so will mean requesting it again without the POST data, so it will not have the intended effect. Just use the HTML you already have in the data argument.
success: function(data) {
$("#con").html(data);
}
On a side note, this PHP code is a reflected XSS vulnerability:
<?php
echo "1".$_POST["action"]."<br/>";
?>
I have this PHP file:
JSONtest.php
<?php
$a=5;
echo json_encode($a);
//This converts PHP variable to JSON.
?>
I want to alert this variable's value using Ajax and JSON, and for that I've written this script:
learningJSON.php
$(document).ready(function(){
$("button").click(function(){
$.ajax({
url: 'JSONtest.php',
type: 'POST',
data: data,
dataType: 'json',
success: function(result){
alert(result);
},
error: function(){
alert("Error");
}
});
});
});
But when I click the button, I get this error message:
learningJSON.php:14 Uncaught ReferenceError: data is not defined
What wrong I'm doing? How can I fix this?
<?php
$a=5;
echo json_encode($a);
//This converts PHP variable to JSON.
?>
Nope, it doesn't. Whats the point in converting a simple number to JSON? It stays the number 5
Now the real problem. Yes your data variable is not defined anywhere in your JavaScript code. If you have no data to send, remove that parameter.
However if you still want to pass some data, define it accordingly then. For example
data: { fname: "John", lname: "Doe" }
Now let's say on your next exercise you want to post form data you can use this nice function named serialize(). This will take all the postable fields from your form and send them along with this request.
data : $("#formID").serialize()
Data variable is not defined, you can delete that
Php file
<?php
$a = $_REQUEST['number'];
echo json_encode($a);
//This converts PHP variable to JSON.
?>
Javascript file
$(document).ready(function(){
$("button").click(function(){
$.ajax({
url: 'JSONtest.php',
type: 'POST',
//data: {'number' : 10}, //this is when you need send parameters to the call, uncomment to send it parameters
dataType: 'json',
success: function(result){
alert(result);
},
error: function(){
alert("Error");
}
});
});
});
I think this one should be perfect for you.
We need 3 files
index.php
login.js
login.php
That mean when user submit [index.php] script js file [login.js] running ajax process script [json] in login.js by collect all data from form input [index.php] and send and run script login.php ... This is powerful script of ajax & json
check code below
index.php
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="login.js" type="text/javascript" charset="utf-8"> </script>
</head>
<body>
<form method="post" id="login" name="login">
Email: <input type="email" id="log-mail" name="log-mail" > <br />
Password: <input type="password" id="log-pass" name="log-pass" > <br />
<button type="submit" >Log in</button>
</form>
</body>
</html>
login.js
$(document).ready(function(){
// #login = login is the name of our login form
$('#login').submit(function(e) {
$.ajax({
type: "POST",
url: "login.php",
data: $('#login').serialize(),
dataType: "json",
success: function(msg){
if(parseInt(msg.status)==1)
{
window.location=msg.txt;
}
else if(parseInt(msg.status)==0)
{
window.location=msg.txt;
}
}
});
e.preventDefault();
});
});
login.php
<?php
if(isset($_POST['log-mail']) && $_POST['log-mail'] != '' && isset($_POST['log-pass']) && $_POST['log-pass'] != '' ) {
$_data_ = 'index.php?user_data='.$_POST['log-mail'];
echo msg_result(1,$_data_);
}else{
$msg_att = "index.php?login_attempt=1";
echo msg_result(0,$msg_att);
}
function msg_result($status,$txt) {
return '{"status":'.$status.',"txt":"'.$txt.'"}';
}
?>
you can see on your url if you
complete all field => ...index.php?user_data=user_data#gmail.com
uncomplete => ...index.php?login_attempt=1
Hope this solve your issue
I am a starter in PHP language. I was trying to develop a small application. For that (lets say, page 1) I was posting some data to a PHP file from the page 1 through an Ajax call.Then I want to access the same value from that PHP file in another HTML file through another Ajax call (let's call page 2).
So I used the session variable for this. I was able to access the values easily in my local-host. Then I uploaded the files in my hosting server. But the application is not working. From the page 1 the data is sending and I am getting the Ajax response accordingly. but am not getting the data in the page2.
Page 1 code is as follows
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
$( document ).ready(function() {
$.ajax({
type: 'GET',
url: 'main.php',
data: {type : 'test' },
dataType:'html',
success: function (data) {
location.assign("mains.html");
}
});
return true;
});
</script>
page 2 is as follows
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
$( document ).ready(function() {
$.ajax({
type: 'GET',
url: 'main.php',
data: { test: 'value' },
dataType:'json',
success: function (data) {
alert(data);
}
});
});
</script>
the server file is as following,(of course its a PHP file)
<?php
session_start();
if(isset($_GET['type'])){
$_SESSION['type'] = $type = $_GET['type'];
echo $_SESSION['type'];
}
if(isset($_GET['test'])){
echo $_SESSION['type'];
}
echo $_SESSION['type'];
?>
Change the extension of your HTML file to .php, then start the file with
<?php
session_start();
?>
In other words: session_start() needs to be called in every PHP file you use.