I'm trying to get this to work, but I am having issues. What am I missing here?
I'm trying to insert some data via jQuery to a local MySQL table. If I run save.php on its own, it inserts a blank row in the DB, so that works. Any ideas?
**index.php**
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<script src="jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$('form#submit').submit(function () {
var nume = $('#nume').val();
$.ajax({
type: "POST",
url: "save.php",
data: "nume="+ nume,
success: function() {
$('#nume').val('');
}
});
return false;
});
});
</script>
</head>
<body>
<form id="submit" method="post">
<p>Nume: <input id="nume" name="nume" type="text"></p>
<p><input id="submitButton" type="button" value="Submit"></p>
</form>
</body>
</html>
**save.php**
<?php
mysql_connect('localhost', 'root', 'root') or die(mysql_error());
mysql_select_db("test") or die(mysql_error());
$nume = htmlspecialchars(trim($_POST['nume']));
$add = "INSERT INTO ajax_test (nume) VALUES ('$nume')";
mysql_query($add) or die(mysql_error());
?>
Are you sure the form is submitting? Your button is not an input type="submit" - it's just a button. It won't submit the form on its own.
If the solution of Scott Saunders does not work try this:
instead of
url: "save.php",
try:
url: "save.php?nume=testvalue",
If that also does not work, check if your PHP script reads the input value out of $_GET['nume'] or $_POST
instead of $_REQUEST['nume']
couple of things you could do to help with troubleshooting.
Stick an alert alert("submit"); in after the $('form#submit').submit(function () {
to see if the form is submitting. Also stick one in the success alert("success"); to see if you're getting a callback. This will show you at what stage it's failing and help you liit your search.
You can also use the firebug plugin for firefox to see what's being sent via ajax, if it's working, to see if you've got any values wrong. Think you need to tick Show XMLHttpRequests in Console
Related
I am trying to run a simple scenario in which: a form is submitted -> jquery ajax request for JSON data -> PHP script reads from the database and encodes to JSON -> data is shown on my page.
the fields on the MySQL are: Name and Password
step 1 - my form - Search.php
<html lang="">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="Query.js"></script>
<title></title>
</head>
<body>
<form method="post" id="formoid" action="">
<input type="text" name="enterpass" placeholder="Enter Password">
<input type="submit" name="subbpass">
</form>
<input type="text" id="showname"><br/>
<input type="text" id="showpassword">
step 2 - my jquery file- Query.js
$(document).ready(function(){
$("#formoid").submit(function(){
alert("form submitted") // this alert goes through
var passid = $("#enterpass").val();
$.ajax({
url: "ModelQuery.php",
method: "POST",
dataType: "JSON",
data: {args: passid},
success: function(data)
{
console.log('ajax successfully sent'); // this alert isn't working
$("#showname").text(data.Name); // data isn't showing here
$("#showpassword").text(data.Password);
console.log(data); // or here ...
}
});
});
});
and lastly, my php -- ModelQuery.php -- I omitted some code lines but that script is the normal script for reading from the database and has worked for me in the past.
<?php
if(isset($_POST['args'])) {
$arg = $_POST['args']
$CON = mysqli_connect('127.0.0.1','root','','testdb');
// ....
$QUERY = "SELECT * FROM testtable where Password = '$arg'";
// ...
while($row = mysqli_fetch_array($RESULT))
{
$jsonresults["Name"] = $row['Name'];
$jsonresults["Password"] = $row['Password'];
}
echo json_encode($jsonresults);
}
the alert in the Jquery script right after the form is submitted does go through, but the ajax itself doesn't show anything, neither on the console nor on my two textboxs.
What am I doing wrong here?
Thank you very much!
I figured out the issue, which consisted of 3 different problems:
1) my input textbox <input type="text" name="enterpass" placeholder="Enter Password"> didn't have id attribute, only name
2) as #RamRaider suggested, I changed it to button and gave it id as well.
3) one of the lines in the php didn't have ; at its end..
Thanks you!
I am trying to learn Ajax. I am inserting some data to mysql database from a Html Form by php. It works nicely. But my ajax part does not work. I get the success message but data dont go to my php file. My html and js code:
<!DOCTYPE html>
<html>
<head>
<title>Insertion of data with Ajax</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </script>
</head>
<body>
<form id="myForm" method="POST" action="ajax-save.php">
Title: <input type="text" name="title" id="title"><br /><br />
Description: <textarea name="description" id="description" rows="20" cols="40"></textarea><br /><br />
Url: <input type="text" name="url" id="url"><br /><br />
<input type="submit" id="submit" name="submit" value="submit">
</form>
<script>
$(document).ready(function(){
$("#submit").click(function(){
$.ajax({
url: 'ajax-save.php',
async: true,
cache: false,
data: $('#myForm').serialize() ,
type: 'POST',
success: function(){
alert("success");
clearForm();
}
});
return false;
});
});
</script>
</body>
</html>
My php codes are working properly. I have tested it without ajax. Here is my php code.
$conn = mysql_connect('localhost', 'root', '');
$db = mysql_select_db('hospital');
if (isset($_POST['title'])) { $title = $_POST['title'];}
if (isset($_POST['description'])) { $description = $_POST['description'];}
if (isset($_POST['url'])) { $url = $_POST['url'];}
if(isset($_POST['submit'])){
if(mysql_query("insert into `wp_upload_video` (`id`, `title`, `description`, `url`) values (NULL, '$title', '$description', '$url')"))
echo "Successfully Inserted";
else
echo "Insertion Failed";
}
Please let me know where is my fault.
When you submit via ajax on a click of the submit button.... that condition is always true.
Checking if $_POST['submit'] is set in the PHP will always result in true because if it is not true the ajax never gets processed.
So... remove the if submit condition in the PHP and handle error notification in the ajax call.
Also, as pointed out by #NiettheDarkAbsol in comments, it's a good idea to add e.preventDefault() to the jquery as well to stop the submit button submitting the form as it normally would and allow the jquery to handle the submit (via ajax).
I've read all the related posted, watched videos, and read tutorials... But I still can't figure this out. I just want to run a mysqli_query insert without a refresh.
No inputs, no variables, just a pre-defined sql insert without a refresh.
Here is the main doc:
<html>
<head>
<script src="inc/scripts/jquery-1.11.3.min.js"></script>
<script>
$("#click").click( function()
{
$.ajax({
url: "click.php",
type: 'POST',
success: function(result) {
//finished
}
});
});
</script>
</head>
<body>
<input type="button" id="click" value="Click">
</body>
</html>
Click.php (Has been tested standalone):
<?php
$db = mysqli_connect("localhost","root","","mytable")
or die("Error " . mysqli_error($db));
mysqli_query($db,"INSERT INTO items VALUES
('','test','test','total test','test','test','test','test')");
?>
This has been driving me crazy... I've read tutorials and watched many videos about ajax... but I can't figure this out.
Thank you for any advice.
To refresh a part of a page you got to bind the success function to a div in the html so add a div with an Id
<div id="myDiv"></div>
And then
$('#like$id').click(function()
{
$.ajax({
url: 'inc/scripts/liker_ajax.php?like=$id',
type: 'GET',
success:function(result){
$('#like$id').addClass('green');
$('#dislike$id').removeClass('red');
$('#myDiv').html(result);
}
});
});
You're binding the event $('#click').click() before there is an element to bind to (since $('#click') isn't loaded yet).
Just move your <script> tag with the click binding event into the <body> underneath the input button and it will work as expected.
You might also want to wrap in a jQuery document ready enclosure like:
$(function() {
});
to make sure it runs when DOM ready.
Try this.
<html>
<head>
<script src="inc/scripts/jquery-1.11.3.min.js"></script>
<script>
function runAjax()
{
$.ajax({
url: "click.php",
type: 'POST',
success: function(result) {
//finished
}
});
</script>
</head>
<body>
<input type="button" id="click" onclick="runAjax()" value="Click">
</body>
</html>
You are binding the event to the element when the element is not exixting yet.
You have 2 options here.
Either move your script block to just below the end of body tag after the element.
Encase your code inside the script block under $(document).ready(function() {
// your code here
});
Also use the console tab under your developer tools to find the root cause if any errors are present.
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>
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.";
?>