I want to execute a shell script from webpage. So I started with a simple arithmatic sum program. Webpage has two fields and a submit button. If user clicks submit button, javascipt validates and then calls php file through ajax. Php file extracts the arguments and call sum.sh with those arguments.
But i'm unable to do it. Here is my code.
design3.html:
<body>
<form action='' method='post'>
<center>
arg1: <input type='text' name='t1' id="arg1"/> <br><br>
arg2: <input type='text' name='t2' id="arg2"/> <br><br>
<input type='submit' name='use_button' value='Sum' onclick="addContent()"/>
</center>
</form>
<script type="text/javascript">
function addContent(){
var a = document.getElementById('arg1').value;
var b = document.getElementById('arg2').value;
if(a == "" || b == "") {
alert("Please fill all fields");
return;
}
var request = $.ajax({
url: "add.php",
type: "POST",
dataType: "html",
data: {functionname: 'add', arguments:[a, b]}
});
request.done(function(msg) {
alert(msg);
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
}
</script>
</body>
add.php:
<?php
if (is_ajax()) {
if( isset($_POST['functionname']) ) {
switch($_POST['functionname']) {
case 'add':
$var1 = $_POST['arguments'][0];
$var2 = $_POST['arguments'][1];
$cmd = 'sh ./sum.sh'.' '.$var1.' '.$var2;
$output = shell_exec($cmd);
echo $output;
break;
}
}
}
function is_ajax() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
?>
sum.sh:
#!/bin/bash
var1=$1
var2=$2
echo `expr $var1 + $var2`
I'm new to this JS and PHP. But tried hard to do this. If I'm testing seperately it's working. When I write html and php in same file without JS then my script is working. If I'm not calling sum.sh script file in php, it is working. Coming to total integration it is failing. I'm getting this error from browser alert Request failed: error.
You POST to the server
functionname: 'add'
It does not match with your server-side test
switch($_POST['functionname']) {
case 'connect':
I thought the problem is in javascript or php. But the problem is in my html code. One of my friend solved this problem.
He told I took submit button. So he changed the type of button submit to button. Now it's working fine.
Change this code:
<input type='submit' name='use_button' value='Sum' onclick="addContent()"/>
to:
<input type='button' name='use_button' value='Sum' onclick="addContent()"/>
Related
I want to use Acymailing Joomla! component installed at example.com/mailer to manage subscriptions from non Joomla site on example.com
In that case I have simple script
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'https://example.com/mailer/index.php?option=com_acymailing&ctrl=sub',
data: $('form').serialize(),
success: function () {
swal('Great success!');
}
});
});
});
and form
<form class="form-inline" action="https://example.com/mailer/index.php?option=com_acymailing&ctrl=sub" method="post">
<div class="form-group">
<label class="sr-only" for="user_name">Email address</label>
<input id="user_name" type="text" name="user[name]" value="" class="form-control" placeholder="Email">
</div>
<div class="form-group">
<label class="sr-only" for="user_email">Password</label>
<input id="user_email" type="text" name="user[email]" value="" class="form-control" placeholder="Password">
</div>
<button type="submit" class="btn btn-default">Sign Up!</button>
<input type="hidden" name="user[html]" value="1" />
<input type="hidden" name="acyformname" value="formAcymailing1" />
<input type="hidden" name="ctrl" value="sub"/>
<input type="hidden" name="task" value="optin"/>
<input type="hidden" name="redirect" value="https://example.com"/>
<input type="hidden" name="option" value="com_acymailing"/>
<input type="hidden" name="visiblelists" value=""/>
<input type="hidden" name="hiddenlists" value="1"/>
</form>
Everything works fine except success, error states...
Joomla Acymailing have sub.php file to handle ajax responses
if($config->get('subscription_message',1) || $ajax){
if($allowSubscriptionModifications){
if($statusAdd == 2){
if($userClass->confirmationSentSuccess){
$msg = 'CONFIRMATION_SENT';
$code = 2;
$msgtype = 'success';
}else{
$msg = $userClass->confirmationSentError;
$code = 7;
$msgtype = 'error';
}
}else{
if($insertMessage){
$msg = 'SUBSCRIPTION_OK';
$code = 3;
$msgtype = 'success';
}elseif($updateMessage){
$msg = 'SUBSCRIPTION_UPDATED_OK';
$code = 4;
$msgtype = 'success';
}else{
$msg = 'ALREADY_SUBSCRIBED';
$code = 5;
$msgtype = 'success';
}
}
}else{
if($modifySubscriptionSuccess){
$msg = 'IDENTIFICATION_SENT';
$code = 6;
$msgtype = 'warning';
}else{
$msg = $modifySubscriptionError;
$code = 8;
$msgtype = 'error';
}
}
if($msg == strtoupper($msg)){
$source = acymailing_getVar('cmd', 'acy_source');
if(strpos($source, 'module_') !== false){
$moduleId = '_'.strtoupper($source);
if(acymailing_translation($msg.$moduleId) != $msg.$moduleId) $msg = $msg.$moduleId;
}
$msg = acymailing_translation($msg);
}
$replace = array();
$replace['{list:name}'] = '';
foreach($myuser as $oneProp => $oneVal){
$replace['{user:'.$oneProp.'}'] = $oneVal;
}
$msg = str_replace(array_keys($replace),$replace,$msg);
if($config->get('redirect_tags', 0) == 1) $redirectUrl = str_replace(array_keys($replace),$replace,$redirectUrl);
if($ajax){
$msg = str_replace(array("\n","\r",'"','\\'),array(' ',' ',"'",'\\\\'),$msg);
echo '{"message":"'.$msg.'","type":"'.($msgtype == 'warning' ? 'success' : $msgtype).'","code":"'.$code.'"}';
}elseif(empty($redirectUrl)){
acymailing_enqueueMessage($msg,$msgtype == 'success' ? 'info' : $msgtype);
}else{
if(strlen($msg)>0){
if($msgtype == 'success') acymailing_enqueueMessage($msg);
elseif($msgtype == 'warning') acymailing_enqueueMessage($msg,'notice');
else acymailing_enqueueMessage($msg,'error');
}
}
}
And JSON looks like on Joomla side registration to the same form by index.php?option=com_acymailing&ctrl=sub
message Subscribe confirmed
type success
code 3
{"message":"Subscribe confirmed","type":"success","code":"3"}
The question is: how to obtain that submission statuses success, error, already submbited etc on external submission form (at example.com page)?
this simple change may do it for you:
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'https://example.com/mailer/index.php?option=com_acymailing&ctrl=sub',
data: $('form').serialize()
}
}).done(function (data) {
swal('Great success!');
});
});
});
I personally like:
$.post("https://example.com...", {
data: $('form').serialize()
}, function(data) {
swal('Great success!');
});
since your result is in JSON, that should be more like:
$.post("https://example.com...", {
data: $('form').serialize()
}, function(data) {
console.log(data); // shows full return object in console
swal('Great success!');
}, "json");
Try the following, I have explained the changes inside comments:
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
var formdata = $(this).serializeArray(); //i really prefer serializeArray better than serialize (up2u)
$.ajax({
type: 'post',
dataType: 'json', //because your data is json
url: 'https://example.com/mailer/index.php?option=com_acymailing&ctrl=sub',
data: formdata,
success: function (d) {//d is the return/response of your url (your question answer)
swal(
d.type+': '+d.code ,
d.message,
d.type
);
},
error: function(d){
swal(
'Oops..' ,
'Something went wrong!', //your json must be in trouble
'error'
);
console.log(d); //delete this in production stage
console.log(d.responseText); //i add this so you will know what happenned exactly when you get this error. delete this too in production stage
}
});
});
});
I don't feel your ajax had issues, what i can see from the Joomla php code, everytime when you request that joomla URL you will always get a response header status code as 200, so your javascript will always land on success block of ajax code, returning with some json based message, when i checked the joomla acymaling (version 5.8.1 for joomla 3.8.3) code for that controller, i saw on line number 74 they are checking if the request is made using ajax, but missing Access-Control-Allow-Origin in php header which will restrict your outside call so you can replace this if condition from :
if($ajax){
#ob_end_clean();
header("Content-type:text/html; charset=utf-8");
}
to
if($ajax){
#ob_end_clean();
header("Content-type:text/html; charset=utf-8");
header("Access-Control-Allow-Origin: *");
}
so to allow calls from any other domain as well, but do remember this can also cause vulnerabilities to you joomla code. also you need to change your HTML form as well add one more hidden field in your HTML :
<input type="hidden" name="ajax" value="1" />
so to allow ajax request by your joomla controller file.
now in your success block of ajax you can make a check something like this :
success:function(data, status, xhr){
var json = $.parseJSON(data);
swal(json.message, json.type);
}
I hope this will help you in acomplishing what you want to, Happy coding.
I also face this type of problem.for solving this type of problem i Put a variable in the success as argument html.
e.g. success(html)
and
console.log(html)
this shows all errors including notices and all. turn on errore_reporting['E_ALL'];. and do not set dataType to 'json' .
Simple solution to your question is :
success: function (data) {
$("#<id_of_tag>").html(data);
}
data : Response returned from the server to your AJAX call
id_of_tag : where you want to display your returned output.
Its just an example, you can decide, what kind of data you want to return and what you want to do with your response.
To answer your question: On Success parameter in function will contain your response.
As in my case, i am returning another JSP page, which i want to display in div tag.
Also check below link : I think it might help you
Best way to check if AJAX request was successful in jQuery
Sorry for my bad english. I'm trying to run a PHP function through an ajax script. The PHP script should run as a FULL NORMAL php script. My idea is to run a recaptcha by a Submit button WITHOUT refreshing the page. That is working, but I found no way to run a normal php script after that. Here is the part of my script.
php:
if( isset( $_REQUEST['startattack'] )){
$secret="********************";
$response=$_POST["g-recaptcha-response"];
$verify=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret={$secret}&response={$response}");
$captcha_success=json_decode($verify);
if ($captcha_success->success==false) {
echo "<script type='text/javascript'>alert('failed!')</script>";
} else if ($captcha_success->success==true) {
echo "<script type='text/javascript'>alert('success!')</script>";
}
}
html:
<form method='post' id="myform">
<center>
<div class="g-recaptcha" data-sitekey="6LfETygTAAAAAMC7bQu5A3ZhlPv2KBrh8zIo_Nwa"></div>
</center>
<button type="submit" id="startattack" name="startattack" onclick="mycall()" class="btn btn-attack">Start Attack</button>
</form>
ajax:
<script>
$(function () {
$('button').bind('click', function (event) {
$.ajax({
type: 'POST',
url: 'post.php',
data: $('button').serialize(),
success: function () {
alert('button was submitted');
type: 'post';
url: 'post.php';
}
});
event.preventDefault();// using this page stop being refreshing
});
});
</script>
I want to check the recaptcha here. If correct, it should echo correct in PHP and I want to add feature later. The same with the false captcha.
I think you can simplify things a bit. You don't return the response in the Ajax is your main problem.
PHP:
Just echo the returned json from the recaptcha (although I have no idea where you get the g-recaptcha-response key/value, you are not sending it anywhere).
if(isset( $_POST['startattack'] )){
$secret = "********************";
// I have added a key/value in the ajax called "sitekey",
// this might be what you are trying to retrieve?
$response = $_POST["g-recaptcha-response"];
echo file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret={$secret}&response={$response}");
exit;
}
AJAX:
I think since the return from the recaptcha is json anyway, just echo it and pick it up on this side:
$(function () {
$('button').bind('click', function (event) {
var statusBlock = $('#status');
statusBlock.text('button was submitted');
$.ajax({
type: 'POST',
url: 'post.php',
data: {
// Not sure if you are trying to pass this key or not...
"sitekey":$('.g-recaptcha').data('sitekey'),
"startattack":true
},
success: function (response) {
var decode = JSON.parse(response);
var alertMsg = (decode.success)? 'Success' : 'Failed';
statusBlock.text('');
alert(alertMsg);
}
});
// using this page stop being refreshing
event.preventDefault();
});
});
Form:
Leave a spot to post the submit status so it doesn't interfere with the return alert dialog window.
<form method='post' id="myform">
<div id="status"></div>
<center>
<div class="g-recaptcha" data-sitekey="6LfETygTAAAAAMC7bQu5A3ZhlPv2KBrh8zIo_Nwa"></div>
</center>
<button type="submit" id="startattack" name="startattack" onclick="mycall()" class="btn btn-attack">Start Attack</button>
</form>
I have form in 100.php with ajax call to 200.php.
<html>
<head>
<!-- include reCAPTCHA API JavaScript library given by Google -->
<script src='https://www.google.com/recaptcha/api.js'></script>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#btn").click(function(event){
event.preventDefault();
var myname = $("#name").val();
var myaddress = $("#address").val();
var yourData ='name='+myname+'&address='+myaddress; // php is expecting name and age
$.ajax({
type:'POST',
data:yourData,//Without serialized
url: '200.php',
success:function(data) {
if(data){
$('#testform')[0].reset();//reset the form
$('#result').html(data); // here html()
//alert('Submitted');
}else{
return false;
}
}
});
});
});
</script>
</head>
<body>
<form method="post" id="testform">
Name: <input type="text" name="name" value="" id="name"/> <br />
Address: <input type="text" name="address" value="" id="address"/>
<!--
place for the reCAPTCHA widget div with your site key
data-theme="dark" attribute - gives dark version
-->
<div class="g-recaptcha" data-sitekey="6LeJ8h8TAAAAAMS9nQX89XccpsC-SDeSycipiaHN"></div>
<input type="submit" name="ok" value="Send" id="btn"/>
</form>
<div id='result'></div>
</body>
200.php does validate captcha and diaplay name and adddress user entered. But my problem is that when I entered name and address, click on captcha. Captha is also validated and shows as in my screenshot. but name and address is not shown on the page. You can also check yourself here: http://raveen.comlu.com/100.php
I am new to Ajax call by PHP. I googled and I can troubleshoot by firebug. Can you say what I am doing wrong here? and steps to troubleshoot by firebug like to check if my ajax call is done, etc? thanks for your help.
Note: when I put all these code in one page without using ajax call. it works fine!!!!! I want this happens without page reload....
output
200.php
<?php
require_once('recaptchalib.php');
if( isset($_POST['ok']) ){
if( isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response']) ){
$secret = "6LeJ8h8TAAAAAB3IFQVQEaoApFe6lvq4Wxlktvn1"; //your secret key
$response = null; //empty response
$reCaptcha = new ReCaptcha($secret); //check secret key is present
$response = $reCaptcha->verifyResponse( $_SERVER['REMOTE_ADDR'], $_POST['g-recaptcha-response'] );
//$response variable will report back with "success"
if( $response!=null && $response->success ){
echo "<h1>Hi ". $_POST['name']. " from ". $_POST['address']. ", thanks for submitting the form!</h1>";
}
}
else{
echo "<h1>Please click on the reCAPTCHA box.</h1>";
}
}
?>
There are few errors in your code, such as:
Look at the following two statements,
if( isset($_POST['ok']) ){...
and
var yourData ='name='+myname+'&address='+myaddress;
You're not sending any variable named ok to 200.php page, so the control won't even enter the if block.
You're validating reCaptcha in the wrong way. From the documentation:
If your website performs server side validation using an AJAX request, you should only verify the user’s reCAPTCHA response token (g-recaptcha-response) once. If a verify attempt has been made with a particular token, it cannot be used again. You will need to call grecaptcha.reset() to ask the end user to verify with reCAPTCHA again.
So you have to use grecaptcha.getResponse() to get the user's response.
And as a sidenote use grecaptcha.reset() to ask the end user to verify with reCAPTCHA again.
Your jQuery/AJAX script should be like this:
<script>
$(document).ready(function() {
$("#btn").click(function(event){
event.preventDefault();
var recaptchaResponse = grecaptcha.getResponse();
var myname = $("#name").val();
var myaddress = $("#address").val();
var yourData = {name: myname, address: myaddress, recaptchaResponse: recaptchaResponse};
$.ajax({
type: 'POST',
data: yourData,
dataType: 'html',
url: '200.php',
success: function(data) {
// reset form
$('#testform')[0].reset();
// display data
$('#result').html(data);
// reset the reCaptcha
grecaptcha.reset();
},
error: function(jqXHR, textStatus, errorThrown){
// error
}
});
});
});
</script>
And on 200.php page, process your AJAX data like this:
<?php
//your site secret key
$secret = '6LeJ8h8TAAAAAB3IFQVQEaoApFe6lvq4Wxlktvn1';
if(isset($_POST['recaptchaResponse']) && !empty($_POST['recaptchaResponse'])){
//get verified response data
$param = "https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$_POST['recaptchaResponse'];
$verifyResponse = file_get_contents($param);
$responseData = json_decode($verifyResponse);
if($responseData->success){
// success
echo "<h1>Hi ". $_POST['name']. " from ". $_POST['address']. ", thanks for submitting the form!</h1>";
}else{
// failure
echo "<h1>You have incorrect captcha. Please try again.</h1>";
}
}else{
echo "<h1>Please click on the reCAPTCHA box.</h1>";
}
?>
Please, can somebody publish a mistakes corrected and tested code for my problem?
Program does - 22.php has the form. When the user enter and click Submit button, the result should be taken from 23.php and displayed in div on 22.php
I already tried solutions below and none of them solve my problem;
1) I changed to: $("#testform").submit(function(event){
2) I included "return false;" at the end to prevent it to actually submit the form and reload the page.
3) clear my browser cache
I can see what happen the program with my computer;
1) I do not get error message after I click submit.
2) I can see the tab of the page reloads quickly and the entered text fields are cleared.
3) No error message or result shows.
<html>
<head>
<title>My first PHP page</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#btn").click(function(event){
event.preventDefault();
var myname = $("#name").val();
var myage = $("#age").val();
yourData ='myname='+myname+'&myage='+myage;
$.ajax({
type:'POST',
data:yourData,//Without serialized
url: '23.php',
success:function(data) {
if(data){
$('#testform')[0].reset();//reset the form
$('#result').val(data);
alert('Submitted');
}else{
return false;
}
};
});
});
});
</script>
</head>
<body>
<form method="post" id="testform">
Name:
<input type="text" name="name" id="name" />Age:
<input type="text" name="age" id="age" />
<input type="submit" name="submit" id="btn" />
</form>
<div id='result'></div>
</body>
</html>
<?php
if ( isset($_POST['name']) ) { // was the form submitted?
echo "Welcome ". $_POST["name"] . "<br>";
echo "You are ". $_POST["age"] . "years old<br>";
}
?>
you don't need to change your php code
try submit form with submit event ...
$("#testform").submit(function(event){
use `dataType:json`; in your ajax ..
yourData =$(this).serialize();
Your php
<?php
if ( isset($_POST['name']) ) { // was the form submitted?
$data['name']= 'welcome '.$name;
$data ['age']= 'you are '.$age;
print_r(json_encode($data));exit;
}
?>
Now In Your Success function
var message = data.name + ' ' + data.age;
$('#result').html(message );
You are sending myname and checking name(isset($_POST['name']) in php.
don't use .value() use .html() for data rendering. and console log the data and see whats request and response using firebug.
Can you try this one?
To be changed
var yourData ='name='+myname+'&age='+myage; // php is expecting name and age
and
$('#result').html(data); // here html()
the code becomes
$(document).ready(function() {
$("#btn").click(function(event){
event.preventDefault();
var myname = $("#name").val();
var myage = $("#age").val();
var yourData ='name='+myname+'&age='+myage; // php is expecting name and age
$.ajax({
type:'POST',
data:yourData,//Without serialized
url: '23.php',
success:function(data) {
if(data){
$('#testform')[0].reset();//reset the form
$('#result').html(data); // here html()
alert('Submitted');
}else{
return false;
}
}
});
});
});
Try formatting your post data like this inside your ajax function.
$.ajax({
type:'POST',
data : {
myname: myname
myage: myage
}
...
}
EDIT
Try removing the ; in
return false;
}
};
to
return false;
}
}
You can change at both end ajax and php:
#PHP:
You can check for correct posted data which is myname and myage not name and age.
<?php
if ( isset($_POST['myname'])) { // was the form submitted?
echo "Welcome ". $_POST["myname"] . "<br>";
echo "You are ". $_POST["myage"] . "years old<br>";
}
?>
or #Ajax:
yourData ='name='+myname+'&age='+myage;
//--------^^^^^^----------^^^^----change these to work without changing php
Just noticed the #result is an div element. So, you can't use .val() but use .html(), .append() etc:
$('#result').html(data);
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 :-)