Ajax Query Isn't Going Through to PHP Script - php

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!

Related

Using AJAX to pass form Submit variable to php page and return output html to DIV

I have been reviewing a lot of the AJAX / PHP documentation and have a quick question for the community to help me understand the fundamentals. Here is a simple form, where a user submits a value. It is sent to a php calculator that squares the value and creates a little echo of the result.
I would like to learn how to simply include the php file into the div "target" after you click submit. Rather than pass back a value, I would like to include the php file in the div instead.
The forums have gotten me this far. Thanks to those who can look over and provide guidance.
square.html:
<!DOCTYPE html>
<html lang="en">
<head>
<title> AJAX Insert test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<form id="calculator" method="post">
What Number would you like to square?
<input type="text" name="input_value">
<input type="submit" value="Go">
</form>
<div id="target"></div>
<script>
$(function() {
$('#calculator').live('submit', function(e) {
e.preventDefault(); // stops form from submitting naturally
$.ajax({
data: $(this).serialize(),
type: 'POST', //'GET' is default, set to 'POST' if you want.
url: 'square.php',
success: function(response) {
$("#target").load("square.php");
}
});
});
</script>
square.php:
<html>
<p>Results:<br><br></p>
</html>
<?php
$input = htmlspecialchars($_POST['input_value']);
$sum = $input * $input;
echo "You wrote " . $input ." <br>";
echo $input . " squared = " .$sum . "<br><br>";
?>
You would want to display the echo of the square.php, which means you have to do the following: $("#target").load(response);

Passing value from ajax to php variable in same page

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>

form fields not getting posted to php file when using jquery

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/

Insert record using jQuery after ajax call doesn't work

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.";
?>

Using jQuery to insert data into a MySQL table

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

Categories