I am having a problem is retrieving data sent to a php file through .ajax() via jquery
Following is my html:
<!-- Jquery tute no 94 onwards -->
<html lang="en">
<head>
<meta charse="utf-8">
<title> jquery4 </title>
<link rel="stylesheet" type="text/css" href="jquery4.css"/>
</head>
<body>
<input id="lo" type="text"> </input>
<input id="ton" type="button" value="Load"> </input>
<div id="content"> </div>
<script type="text/javascript" src="jquery.js"> </script>
<script type="text/javascript" src="jquery4.js"> </script>
</body>
</html>
My jquery4.js is:
$(document).ready(function()
{
$('#ton').click(function()
{
var nm= $('#lo').val();
$.ajax({url: 'page.php', data1: 'name='+nm, success: function(data2)
{
$('#content').html(data2);
}
});
});
});
My page.php is:
<?php
if(isset($_GET['data1']))
{
echo $namer= $_GET['data1'];
}
?>
All the above files are in the same folder, and I have xampp installed.
I guess the error is somewhere in the jquery file where I call the
ajax() function
jQuery ajax doesn't take a data1 parameter. It takes a data parameter, which should be an object of name-value pairs.
$.ajax({
url: 'page.php',
data: {
data1: 'name=' + nm,
},
success: function(data2) {
$('#content').html(data2);
}
});
$.ajax({
type: "GET",
url: "page.php",
data: {
data1: 'name=' + nm,
}
,
success: function(data2) {
$('#content').html(data2);
}
});
Try this:
$(document).ready(function() {
$('#ton').click(function() {
var nm= $('#lo').val();
$.ajax({
url: 'page.php?name=' +nm,
success: function(data2) {
$('#content').html(data2);
}
});
});
});
You don't have to tell jQuery to use GET, as it defaults to that, if nothing else is specified.
So the ajax function does not take an argument called data1, but 'data', this is mostly used for other methods as POST, PUT and DELETE.
I prefer also sending GET requests with a normal query string, like the above example.
You can then check for get GET parameter with PHP, using $_GET['name']
Related
This question already has answers here:
jQuery Ajax POST example with PHP
(17 answers)
Closed 7 years ago.
To make this understandable I made an sample code because my actual code is much bigger.
Basically what I want to accomplish is to run my PHP script that edits an XML file using ajax. This is because I need to do this inside a javascript in my real project.
This is what I have so far:
the .php file containing the ajax function:
<!DOCTYPE html>
<html>
<head>
<script>
function editXMLDoc()
{
$.ajax({
url: "sensors.php",
context: document.body
}).done(function() {
$( this ).addClass( "done" );
});
}
</script>
</head>
<body>
<button type="button" onclick="editXMLDoc()">Endre XML</button>
</body>
</html>
And here is the php script writing to xml:
<?php
include 'sensor.php';
$b=new sensor();
$arr=$b->load('sensor.xml');
for($i=0,$ms=count($arr);$i<$ms;$i++)
{
if($arr[$i]['fields']['status']=='1')
{
$arr[$i]['fields']['status']='0';
}else{
$arr[$i]['fields']['status']='1';
}
}
echo "Completed<br/>";
//3. save array to xml
$b->save('sensor.xml',$arr);
?>
I know the script is working so I am pretty sure the prob is the connection between the ajax function and the php script.
Can anyone help me out?
Try this code... actually you did not attached jQuery library.
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
jQuery(document).ready(function($){
var resp = $("#response");
$.ajax({
type: "POST", // Method type GET/POST
url: "sensors.php", //Ajax Action url
data: {},
// Before call ajax you can do activity like please wait message
beforeSend: function(xhr){
resp.html("Please wait...");
},
//Will call if method not exists or any error inside php file
error: function(qXHR, textStatus, errorThrow){
resp.html("There are an error");
},
success: function(data, textStatus, jqXHR){
resp.html(data);
}
});
});
</script>
</head>
<body>
<div id="response"></div>
</body>
</html>
Use AJAX like this:
<script type="text/javascript">
jQuery(document).ready(function($){
$('.rt11').click(function(){
$.ajax({
type: "POST", // Method type GET/POST
url: "sensors.php", //Ajax Action url
data: {yourKey: "yourValue", yourKey1: "another value"},
// Before call ajax you can do activity like please wait message
beforeSend: function(xhr){
console.log("Please wait...");
},
//Will call if method not exists or any error inside php file
error: function(qXHR, textStatus, errorThrow){
console.log("There are an error");
},
success: function(data, textStatus, jqXHR){
console.log(data);
}
});
});
});
</script>
I think there is no problem in code but sometime in large code the min.js file did not include properly. please try the below code. there is no need to change sensors.php file.
<!DOCTYPE html>
<html>
<head>
<script>
$(document).ready(function(){
$('.rt11').click(function(){
$.ajax({
url: "sensors.php",
context: document.body
}).done(function(html) {
$( this ).addClass( "done" );
});
});
});
</script>
</head>
<body>
<button type="button" class="rt11">Endre XML</button>
</body>
</html>
HTML:
<button type="button" id="idButton">Endre XML</button>
JS:
$("#idButton").click(function(){
$.ajax({
url: 'sensors.php',
dataType: "xml", //if it returns a xml file
success: function (data) {
// everything is ok
alert(data)
},
error: function (xhr, status, error) {
// Something went wrong
if (xhr.status > 0) alert('Error: ' + status);
}
});
})
Try this i think you missed to include the jQuery library file.Get post data to your php file after ajax call.
<!DOCTYPE html>
<html>
<head>
//include the jQuery library file
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
function editXMLDoc()
{
var myvalue='123';
$.ajax({
url: "sensors.php",
context: document.body,
data: {myvalue:myvalue},
}).done(function() {
$( this ).addClass( "done" );
});
}
</script>
</head>
<body>
<button type="button" onclick="editXMLDoc()">Endre XML</button>
</body>
</html>
I'm not able to get typeahead to work on my website, here what I have tried.
My html and code
<html>
<head>
<title>typeahead</title>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/typeahead.js/0.10.4/typeahead.bundle.min.js"></script>
</head>
<body>
<input id="typeahead" type="text" data-provide="typeahead" autocomplete="off">
<script type="text/javascript">
$(document).ready(function() {
$('#typeahead').typeahead({
source: function (query, process) {
$.ajax({
url: 'data.php',
type: 'get',
dataType: 'JSON',
async: true,
data: 'query=' + query,
success: function(data) {
console.log(data);
process(data);
}
});
}
});
});
</script>
</body>
</html>
when I query data.php in my browser, I get the following
http://localhost/data.php?query=a
output
["admin","admin2"]
Yet, I'm not sure why its not working, backend works, I have checked my code many times, I wonder what I'm missing.
Your help is highly appreciated.
$.ajax({
url: 'data.php', // Just try url:'data.php?query=a'
type: 'get',
dataType: 'JSON',
async: true,
data: {'query' : query}, // changed
success: function(data) {
console.log(data);
process(data);
}
});
Typically typeahead uses handlebar.js as well so I included that here. I updated your code to match the remote example here (though I didn't actually test the code). Hopefully that will get you pointed in the right direction.
<html>
<head>
<title>typeahead</title>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/typeahead.js/0.10.4/typeahead.bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0/handlebars.min.js"></script>
</head>
<body>
<input id="typeahead" type="text" data-provide="typeahead" autocomplete="off">
<script type="text/javascript">
$(document).ready(function() {
var mySearch = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
prefetch: 'data.php',
remote: 'data.php?query=' + query
});
mySearch.initialize();
$('#typeahead').typeahead(null, {
name: 'best-pictures',
displayKey: 'value',
source: mySearch.ttAdapter()
});
});
</script>
</body>
</html>
You can write you ajax call like this with Bootstrap 2.1.0 up to 2.3.2:
$(document).ready(function(){
$('#typeahead').typeahead({
source: function (typeahead, query) {
return $.get('data.php', { 'query': a }, function (data) {
return typeahead.process(data);
});
}
});
});
with Bootstrap 3.0 type is no longer bundled with it, So you can use Ajax Type-ahead
its very easy to use:
$("#ajax-typeahead").typeahead({
ajax: "/path/to/source"
});
This is my code and i want to pass javascript variable with ajax to php when i click submit button then the result doesn't show var_data variable from javascript What code is wrong?
This is edit order one before everybody help me
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#sub').click(function() {
var var_data = "Hello World";
$.ajax({
url: 'http://localhost/ajax/PassVariable.php',
type: 'GET',
data: { var_PHP_data: var_data },
success: function(data) {
// do something;
}
});
});
});
</script>
</head>
<body>
<input type="submit" value="Submit" id="sub"/>
<?php
$test = $_GET['var_PHP_data'];
echo $test;
?>
</body>
</html>
and this is source code now
<?php
if (isset($_GET['var_PHP_data'])) {
echo $_GET['var_PHP_data'];
} else {
?>
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
$(document).ready(function() {
$('#sub').click(function() {
var var_data = "Hello World";
$.ajax({
url: 'http://localhost/test.php',
type: 'GET',
data: { var_PHP_data: var_data },
success: function(data) {
// do something;
$('#result').html(data)
}
});
});
});
</script>
</head>
<body>
<input type="submit" value="Submit" id="sub"/>
<div id="result">
</body>
</html>
<?php } ?>
this statement if(isset($_GET['var_PHP_data'])) output false and then show Hello World What should i do to do for isset($_GET['var_PHP_data']) is true?
Your solution has PHP issues: you don't check if the data exists, and also, you don't do anything with the result. I've modified the script to do the following:
Check if the var_PHP_data var is set (in PHP, on the server).
If yes, just send a blank text response containing that data.
If no, then draw the form and everything else.
In the form, I've created a #result div.
Ajax response will be shown in this div.
Also make sure that you host the script at localhost and that it is called test.php. To make sure this is resilient, you can change the Ajax URL to
<?php echo $_SERVER['PHP_SELF'];?> to make sure that you'll hit the correct script.
<?php
if (isset($_GET['var_PHP_data'])) {
echo $_GET['var_PHP_data'];
} else {
?>
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js">
<script>
$(document).ready(function() {
$('#sub').click(function() {
var var_data = "Hello World";
$.ajax({
url: 'http://localhost/test.php',
type: 'GET',
data: { var_PHP_data: var_data },
success: function(data) {
// do something;
$('#result').html(data)
}
});
});
});
</script>
</head>
<body>
<input type="submit" value="Submit" id="sub"/>
<div id="result">
</body>
</html>
<?php } ?>
Try jQuery Form its this will help to solve many problems.
For you question: try url without domain name, add tags 'form', change event click to submit, add data type
what are the contents of PassVariable.php ? if is the same where you have they jquery bit wont work coz php will print all the page again, if the file is different try
success: function(data) {
alert('databack = '+ data);
}
Try placing your input into a form and attaching the ajax call to the form onsubmit event. The way it happens in the provided happen is when you click in the field, in which case it submits before you can write anything really.
$(document).ready(function() {
$('#brn').click(function() {
var var_data = "Hello World";
alert("click works");
$.ajax({
url: 'http://localhost/ajax/PassVariable.php',
type: 'GET',
data: { x: var_data },
success: function(data) {
alert(data);
}
});
});
});
change it to this code
then in PassVariable.php put
make button
<input type="button" id="btn" value="click me" />
it should work because it is very basic example. If it doesn't work check your console if there are any JavaScript errors and remove them.
I am new to this jquery and phonegap.I am finding little difficulty in parsing the data from .php file from a local server.Please help me in doing so.
This is my index.html page:
<!DOCTYPE HTML>
<html>
<h2>JSON Parser</h2>
<script type="text/javascript" src="jquery.js"/></script>
<script type="text/javascript">
function parseJSON()
{
var json;
$.ajax({
type: 'POST',
url: 'http://192.168.1.12/training/services/login.php',
cache: false,
// data: $('#abc').serialize(),
dataType: 'json',
success: function(data){
alert(data);
$('#data').append(data);
}
});
}
</script>
</head>
<body onload="parseJSON()">
<p>Employee's Information</p>
<form id="abc" method ="post">
<div id="data"></div>
</form>
</body>
</html>
The login.php file contains a sample json data's as follows:
{"username":"test#test.com","password":"password"}
If you are trying to get the data using php and ajax use jsonp,
in your PHP file add callback for json output:
echo $_GET['callback'] . '('.json_encode($data).')';exit;
apppend callback in your ajax call
Javascript:
$.ajax({
url: 'http://192.168.1.12/training/services/login.php?callback=?',
cache: false,
type: "GET",
dataType: "jsonp",
contentType: "application/json; charset=utf-8",
success: function(data) {
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
And last but not least, dont forget to add domain white list for your localhost
in corodova.xml:
<access origin="http://192.168.1.12"/> OR
<access origin="*"/> to allow all domains
If I have understand correctly you may do something like that.
If your php page send data to your html one, you may use GET instead of POST
<!DOCTYPE HTML>
<html>
<h2>JSON Parser</h2>
<script type="text/javascript" src="jquery.js"/></script>
<script type="text/javascript">
function parse()
{
var json;
$.ajax({
type: 'GET',
url: 'http://192.168.1.12/training/services/login.php',
cache: false,
dataType: 'json',
success: function(data)
{
var obj = jQuery.parseJSON(data);
$('#data').html(obj["username"]);
}
});
}
</script>
</head>
<body onload="parse()">
<p>Employee's Information</p>
<form id="abc" method ="post">
<div id="data"></div>
</form>
</body>
</html>
Okay, what have I done wrong here?
I'm trying to .POST data from a Form with JQuery $.ajax function and return json data. But every time the post data is null.
Here is the HTML/JQuery Part
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/redmond/jquery-ui.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js"></script>
</head>
<body>
<form action="testform" method="post">
OLD ID:
<input id="OldID" name="OldID" type="text"><br>
NewID:
<input id="NewID" name="NewID" type="text"><br>
<input id="do" name="do" type="button" value="Get New ID">
</form>
<script type="text/javascript">
var CID = $('#OldID').val();
$(document).ready(function(){
$('#do').click(function(){
sendValue();
});
function sendValue(CID){
$.ajax({
type: 'POST',
url: 'getNewID.php',
data: {OldID: CID},
dataType: 'json',
cache: false,
success:
function(data){
$('#NewID').val(data.NewID);
}
}) }
});
</script>
</body>
</html>
Here's the PHP page
<?php
if (isset($_POST['OldID'])){
$value = $_POST['OldID'];
}else{
$value = "ELSE VALUE";
}
echo json_encode(array("NewID"=>$value));
?>
I'm sure this is a simple mistake on my part but I'm just going in circles at this point.
Thanks in advance!
$('#do').click(function(){
sendValue();
});
should be:
$('#do').click(function(){
sendValue("VALUE TO SEND TO THE SERVER");
});
because
function sendValue(CID){
takes the scope of CID which it seems you might think should be this var CID = $('#OldID').val();
Your mistake is that you are getting the value of the OldID field in your script, and not on some event handler method. This causes when the script is loaded (when the page is being viewed), the value of the text input is kept on variable CID. and when the user clicks on the #do button, then the value of CID is still the same as the one when the page was loaded. So no value is stored in CID variable, so no value is sent via AJAX.
Define another function (Say sendOldID) that reads the value of the text input in the CID variable, and then calls the sendValue() method with CID paramter. The use that function as the event handler of the #do button clicked.
<script type="text/javascript">
$(document).ready(function(){
$('#do').click(function(){
sendOldID();
});
function sendOldID() {
var CID = $('#OldID').val();
sendValue(CID);
}
function sendValue(CID) {
$.ajax({
type: 'POST',
url: 'getNewID.php',
data: {OldID: CID},
dataType: 'json',
cache: false,
success:
function(data){
$('#NewID').val(data.NewID);
}
}) }
});
</script>