Since 3days i am trying my best to get the solution from Ajax & PHP, i tried all tutorial but i am unable to get the solution, i am new to Ajax,Jquery but my question is really simple to you all.
i have developed website using jquery & PHP, i have created menu using HTML (ul, li) so what i want is, if i click on menu item ajax should send value to php variable and then execute php function, but all this should happen in same page,..
Please help me to resolve the issues.
So far, I have tried the following:
JavaScript:
<script type="text/javascript">
$("#btn").click(function() {
var val = "Hi";
$.ajax ({
url: "oldindex.php",
data: val,
success: function() {
alert("Hi, testing");
}
});
});
</script>
PHP and HTML:
<input type="submit" id="btn" value="submit">
<form name="numbers" id="numbers">
<input type="text" name="number" id="number">
</form>
<div id="number_filters">
1
2
3
</div>
so if i click on href, i should get the value to php variable it should happen in same page only
index.php page
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#btn").click(function() {
var val = "Hi";
$.ajax ({
url: "ajax.php",
data: { val : val },
success: function( result ) {
alert("Hi, testing");
alert( result );
}
});
});
});
</script>
<input type="submit" id="btn" value="submit">
<form name="numbers" id="numbers">
<input type="text" name="number" id="number">
</form>
<div id="number_filters">
1
2
3
</div>
ajax.php page
<?php
echo ( $_GET['val'] );
Let's see:
1- If you are doing a AJAX call, your page won't be refreshed. So if you try to send variables to the same page that makes the AJAX call it won't work, here's why. When you are able to see the page and execute the AJAX call, the code is already on the client side (your web explorer), there no PHP will be seen or executed (PHP is executed on the server only), so it's imposible for the same page to capture and process variables you pass to it using AJAX (since AJAX WON'T refresh the page, that's the point of AJAX).
2- If you are using AJAX you don't have to call to the same page. Call to another PHP, it will make the server side work for you, then return the result:
success: function(data) {
alert("Hi, server returned this: "+data);
}
3- When you pass variables using AJAX you have to assign the variable a name, so it can be read in the PHP side:
data: {value: val},
4- For what you have in your question, you don't start the AJAX call clicking a href, you have the AJAX function linked to a input type=submit, it also is outside a form.. so let's do this better:
<button id="btn">submit</button>
Here is your solution as given sample code:
<?php if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
echo $_GET['q'];
exit;
} ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type='text/javascript' src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$("#btn").click(function(e) {
e.preventDefault();
var val = "Hi";
$.ajax ({
url: "test8.php",
// wrong query. you are not passing key , so here q is key
data: 'q=' + val,
success: function(returnResponseData) {
alert('Ajax return data is: ' + returnResponseData);
}
});
});
});
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<form name="numbers" id="numbers">
<input type="text" name="number" id="number">
<input type="submit" name='button' id="btn" value="submit">
</form>
</body>
</html>
Related
I am beginner to ajax world and trying to call contents from php page using $.ajax() function and the code couldn't executed. the html page i used:
<!DOCTYPE html>
<html>
<head>
<title>AJAX</title>
</head>
<body>
<div >
<input type="text" name="search" id="search">
<br>
<br>
<h2 id="result"></h2>
</div>
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<script src="js/script.js"></script>
</body>
</html>
the JQuery code i used in the script.js:
$(document).ready(function() {
$('#search').keyup(function () {
var search = $('#search').val();
$.ajax({
url:'search.php',
//the page to which the request will go to
data:{search: search},
type: 'POST',
success:function(data) {
if(!data.error){
$('#result').html(data);//the h2 we want to echo it uing the ajax
}
}
});
});
});
the search.php page contain:
$search = $_POST['search'];
echo $search;
the code not executed. What should I do.
I see some issue in your response from PHP code and in ajax side success code.
You are not sending in response JSON format so data.error is meaningless.
so in your success callback code should be like this.
success:function(data) {
$('#result').html(data);//the h2 we want to echo it uing the ajax
}
Follow jQuery Ajax Document :
An alias for method. You should use type if you're using versions of jQuery prior to 1.9.0
type: 'POST'
But you are using 2.0 so i think this will work :
method: 'POST'
jQuery Documents
I have an HTML file that has a form with two fields. These fields' value should be posted to a PHP and this PHP should be fetched from the HTML using JQuery. This is what I implemented.
My HTML file:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.1.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#first").load("result_jquery.php");
});
});
</script>
</head>
<body>
<div id="first"></div>
<div>
<form method="POST" id="myForm">
Name: <input type="text" name="name"/><br/>
Number: <input type="text" name="number"/><br/>
<button>submit</button>
</form>
</div>
</body>
This is my result_jquery.php
<?php
$n = $_POST["name"];
echo "hello ".$n;
?>
When I click the submit button, the hello is getting printed. But the name is not getting printed. Can you please help me with this. I don't know where I am going wrong.
I think that the use of the button element is the worry and the code that i will put now it is working properly as you need so try this and tell me the result :)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.1.min.js"></script>
<script>
$(document).ready(function(){
$("#button").click(function(){
var n = $('[name="namee"]').val();
var nb = $('[name="number"]').val();
$("#first").load("result_jquery.php",{'namee':n,'number':nb},function(data){});
});
});
</script>
</head>
<body>
<div id="first"></div>
<div>
<form method="POST" id="myForm">
Name: <input type="text" name="namee"/><br/>
Number: <input type="text" name="number"/><br/>
<input type="button" value="Submit" id="button" />
</form>
</div>
</body>
</html>
copy this code:
<script type="text/javascript">
$(document).ready(function() {
$("#send").click(function() {
$.ajax({
type: "POST",
data : "name="+$( '#name' ).val(),
url: "result_jquery.php",
success: function(msg) {
$('#first').html(msg);
}
});
});
});
</script>
change this in form
<form method="POST" id="myForm">
Name: <input type="text" id="name" name="name"/><br/>
Number: <input type="text" id="number" name="number"/><br/>
<input type="button" id="send" value="Submit">
</form>
just try that and tell me the result :)
var n = $('[name="name"]').val();
var nb = $('[name="number"]').val();
$('#error').load("result_jquery.php", {'name':n,'number':nb},function(data){});
Note try to change the element name for the name field from "name" to "namee" and apply changes as needed look like this :
var n = $('[name="namee"]').val();
var nb = $('[name="number"]').val();
$('#error').load("result_jquery.php", {'namee':n,'number':nb},function(data){});
and the result_jquery.php file :
<?php
$n = $_POST["name"];
echo "hello ".$n;
?>
From the jQuery documentation on load:
This method is the simplest way to fetch data from the server. It is
roughly equivalent to $.get(url, data, success) except that it is a
method rather than global function and it has an implicit callback
function. When a successful response is detected (i.e. when textStatus
is "success" or "notmodified"), .load() sets the HTML contents of the
matched element to the returned data. This means that most uses of the
method can be quite simple:
You are performing a HTTP GET with that method, and not a POST.
My suggestion would be if you want to send an AJAX request to your server with information in it, get used to using the long form jQuery AJAX:
$.ajax({
data: 'url=encoded&query=string&of=data&or=object',
url: 'path/to/server/script.php',
success: function( output ) {
// Handle response here
}
});
For more info, see jQuery documentation: http://api.jquery.com/jQuery.ajax/
I'm learning how to integrate JQuery, AJAX and PHP together.
My problem is that my success function isn't getting any value from the parameter and just getting a '0'. I'm not really sure what I'm doing wrong either, but I have just been following this tutorial JQuery & PHP Tutorial and just copied how he got the value from the PHP code using echoes and a parameter variable r.
I have tried searching for the solution, but I'm not sure if any of the results are relevant to what I am doing. I tried following some of their advice but none seems to work (the promise thing for jQuery)
I hope someone can enlighten me what I am doing wrong as I am eager to learn more PHP and jQuery.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script>
$(function () {
jQuery("form").submit(function(e) {
var input = $("#input").val();
var url = 'input=' + input;
$.ajax({
type: "POST",
url: "process.php",
data: url,
success: function(r) {
$("#output").text(function(r) {
return r;
});
}
});
e.preventDefault();
});
});
</script>
<title>Insert title here</title>
</head>
<body>
<form action="process.php" method="post">
Inputs:<br />
<textarea rows="15" cols="60" id="input" name="input">Some text...
</textarea><br /><br />
Start:
<input type="text" id="start" name="start" />
End:
<input type="text" id="end" name="end" /><br />
<input type="submit" id="submit" name="submit" value="Submit">
</form>
<p id="output">Output: Some Random Text</p>
</body>
</html>
PHP:
require 'parser.php';
$parser = new Parser();
#header('index.php');
$hash = $parser->parse($_POST['input']);
$keys = array_keys($hash);
foreach($keys as $key) {
echo "$key ->";
$dests = $hash[$key];
foreach($dests as $dest) {
echo " $dest";
}
echo "<br />";
}
?>
<script>
$(function () {
jQuery("form").submit(function(e) {
var input1 = $("#input").val();
var url = {'input' : input1}; // a little change to the data parameter
$.ajax({
type: "POST",
url: "process.php",
data: url,
success: function(r) {
// $("#output").text(r); //<--- changed to this
$("#output").html(r); // this is better as you output html
}
});
e.preventDefault();
});
});
</script>
for jquery text(), use the return value from the server directly. If you are outputting html use jquery html() instead
jquery-ajax: pass values from a textfield to php file and show the value
i made a variation of the link above this time using only one file and no div tag.
test.php
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#submit").click(function(){
var dataString = $("#inputtext").val();
$.ajax({
type: "POST",
url: "test.php",
data: "dataString=" + dataString,
success: function(result){
window.location.reload(true);
}
});
window.location.reload(true);
});
});
</script>
</head>
<body>
<input type="text" id="inputtext">
<input type="button" id="submit" value="send">
<?PHP
if(isset($_POST['dataString'])){
$searchquery = trim($_POST['dataString']);
print "Hello " . $searchquery;
}
?>
</body>
</html>
value from dataString won't show. why?
Sorry for the question, but what's the point of using ajax to reload the same page?? Use it to call another page and then load the result, not the way you're doing it.
Try this
In test.php:
$("#submit").click(function(){
var dataString = $("#inputtext").val();
$.ajax({
type: "POST",
url: "anothepage.php",
data: dataString,
success: function(result){
$('#result').html(result).
}
});
return false; //so the browser doesn't actually reload the page
});
And you should actually use a form, not just inputs. And use the name attribute for them, or php won't pick the value! ID is for javascript and css.
<form method="POST" action="">
<input type="text" id="inputtext" value="" name="inputtext">
<input type="submit" id="submit" value="send" name="submit">
</form>
<div id="result"> <!-- result from ajax call will be written here --> </div>
In anotherpage.php:
if(isset($_POST['inputtext'])){
$searchquery = trim($_POST['inputtext']);
echo htmlentities($searchquery); // We don't want people to write malicious scripts here and have them printed and run on the page, wouldn't we?
}
When you refresh the page using JavaScript, you lose any POST parameters you sent to the page. That is one reason why you never saw any valid results.
You are also missing the benefits from using AJAX - A motivating reason to deploy AJAX is to remove the requirement to refresh the page while still accepting and processing user input.
If you prefer to process the data from AJAX on the same page that is serving the HTML, here is a working example based on your supplied code.
<?php
if( isset($_POST['dataString']))
{
echo 'Hello ' . trim( $_POST['dataString']);
exit;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />
<title>Testing jQuery AJAX</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#submit").click(function(){
var dataString = $("#inputtext").val();
$.ajax({
type: "POST",
url: "test.php",
data: "dataString=" + dataString,
success: function( data){
alert( data);
}
});
});
});
</script>
</head>
<body>
<form action="test.php" method="post">
<input type="text" id="inputtext" />
<input type="button" id="submit" value="send" />
</form>
</body>
</html>
I have an insert and load record (jQuery & PHP) script working fine without using AJAX. but after the AJAX call, insert (jQuery) doesn't work.
This is my code:-
$(".insert").live("click",function() {
var boxval = $("#content").val();
var dataString = 'content='+ boxval;
if(boxval==''){
alert("Please Enter Some Text");
}
else{
$.ajax({
type: "POST",
url: "demo.php",
data: dataString,
cache: false,
success: function(html){
$("table#update tbody").prepend(html);
$("table#update tbody tr").slideDown("slow");
document.getElementById('content').value='';
}
});
}
return false;
});
$(".load").live("click",function() {
$.ajax({
type: "POST",
url: "test.php",
success: function(msg){
$("#container").ajaxComplete(function(event, request, settings){
$("#container").html(msg);
});
}
});
});
});
Definitely recommend using your browsers dev tools to examine the exact request that is submitted and see if there is a problem there first.
You might also want to change the way you pass the dataString to the ajax request.
If your boxval has a "&" in it then you'll end up with an incorrectly formatted string. So, try initialising data instead as:
var data = {};
data.content = boxval;
This will ask jQuery to escape the values for you.
I'd be curious to see your form markup and your back-end PHP code; it may provide a clue.
Often I'll have a form variable called 'action', just to tell the PHP code what I want it to do (especially if that PHP script is a controller for many different actions on an object). Something like <input type="hidden" name="action" value="insert"/> or even multiple <input type="submit" name="action"/> buttons, each with a different value. In the PHP code I'll have something like:
switch ($_POST['action']) {
case 'insert':
// insert record and send HTML
break;
// other actions
}
If you've done something like this, perhaps the PHP is looking for the presence of a variable that doesn't exist.
Without being able to look at your code, I'd highly recommend the incredibly handy jQuery Form Plugin http://jquery.malsup.com/form/ . It allows you to turn a form into an AJAX form, formats your data properly, and doesn't forget the data from any of your form elements (except <input type="submit"/> buttons that weren't clicked on, which is the same behaviour that a non-AJAX form exhibits). It works just like the standard $.ajax() method.
I solved the problem
I replaced this code
$("#container").ajaxComplete(function(event, request, settings){
$("#container").html(msg);
});
with
$("#container").html(msg);
Thank you very much for your answers
<!--
To change this template, choose Tools | Templates
and open the template in the editor.
-->
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.clicker').click(function(){
var fname = $('.fname').val();
var lname = $('.lname').val();
var message=$('.message').val();
$.ajax({
type:"POST",
url: "submit.php",
cache:false,
data: "fname="+fname+"&lname="+lname+"&message="+message,
success: function(data){
$(".result").empty();
$(".result").html(data);
}
});
return(false);
});
});
</script>
</head>
<body>
<div>Data Form</div>
<form id="form1" name="form1" method="post" action="">
<input name="fname" type="text" class="fname" size="20"/><br />
<input name="lname" type="text" class="lname" size="20"/><br />
<div class="result"><textarea name="message" rows="10" cols="50" class="message"> </textarea></div>
<input type="button" value="calculate" class="clicker" />
</form>
</body>
</html>
submit.php
<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("ajaxdb",$con);
$fname=$_REQUEST['fname'];
$lname=$_REQUEST['lname'];
$message=$_REQUEST['message'];
$sql="insert into person(fname,lname,message) values('$fname','$lname','$message')";
mysql_query($sql) or die(mysql_error());
echo "The data has been submitted successfully.";
?>