Trying to display PHP echo in HTML with JSON - javascript

I'm trying to display two PHP echo messages from a seperate PHP file onto my HTML body page. Whenever you click the submit button the echo message should popup in the HTML page without redirecting me to the PHP page.
I need to connect to my two files through Javascript so I wrote a script attemtping to connect the HTML file with the PHP file.
My HTML:
<div id="formdiv">
<form action="phpfile.php" method="get" name="fillinform" id="fillinform" class="js-php">
<input id="fillintext" name="fill" type="text" />
<input type="submit" id="submit1" name="submit1">
</form>
</div>
phpfile.php:
$q = $_GET['fill'];
$y = 2;
$work = $q * $y;
$bork = $work * $q;
echo json_encode($work) ."<br>";
echo json_encode($bork);
Javascript:
$(".js-php").submit(function()
var data = {
"fill"
};
data = $(this).serialize() + $.param(data);
$.ajax({
type:"GET",
datatype:"json",
url:"phpfile.php",
data: data,
success: function (data){
$(".formdiv").html(
""
"Your input: ")
}

You attached your logic to .submit() event and if you don't prevent default action, the form will be submitted to server. You can prevent it that way:
$(".js-php").submit(function(e) {
// your code goes here
e.preventDefault();
});

You'll have to append the data to your div like this:
success: function (data) {
$(".formDiv").append("Your input: " + data);
}

As per your html you should try this below code :
If you want to replace the whole html inside the div having id="formdiv"
success: function (data){
$("#formdiv").html("Your input: "+data)
}
or
success: function (data){
$("#formdiv").text("Your input: "+data)
}
If you want to append data to the div having id="formdiv"
success: function (data){
$("#formdiv").append("Your input: "+data)
}

Add curly braces after $(".js-php").submit(function(e) and close it after your ajax ends.
Add e.preventDefault() before you call ajax so it will not redirect
you to phpfile.php
Add alert(data) inside your function called at success of ajax.
there is a syntax error n line $(".formdiv").html("""Your input: ");
Your updated code should look like.
$(".js-php").submit(function(e){
var data = {
"fill"
};
data = $(this).serialize() + $.param(data);
$.ajax({
type:"GET",
datatype:"json",
url:"phpfile.php",
data: data,
success: function (data){
alert(data);
}
}

Related

Get and display results of PHP using jQuery/AJAX

I have a Leaflet map, and a text input. I want to take the address from the textbox, run it through a PHP script, and get the result all through jQuery.
Here is my form:
<form id="mapcheck" method="POST" action="geo.php">
<input id="largetxt" type="text" name="checkAddress">
<input id="button" type="submit" name="submit" value="Check">
</form>
Here is part of the PHP:
<?php
if (isset($_POST["checkAddress"])) { //Checks if action value exists
$checkAddress = $_POST["checkAddress"];
$plus = str_replace(" ", "+", $checkAddress);
$json = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address=' . $plus . '&key=GMAPSKEY');
$obj = json_decode($json);
$mapLat = $obj->results[0]->geometry->location->lat;
$mapLng = $obj->results[0]->geometry->location->lng;
$coords = ('' . $mapLat . ', ' . $mapLng . '');
return $coords;
}
?>
And the jQuery:
$(document).ready(function() {
$("#button").click(function(){
$.ajax({
url: "geo.php",
method: "POST",
data: {
checkAddress: $("#largetxt").val()
},
success: function(response){
console.log(response);
}
});
});
});
I need to listen on submit of the form via jQuery (NOT PHP), run it through a geocode script, then take that result and put it through regular JavaScript (Leaflet map.) I have played around with the AJAX feature of jQuery to no avail. There is a very simple solution to this, but I have not figured it out.
UPDATE: Problem resolved, thanks Vic.
You would need AJAX. Remove the form element but keep the inputs.
$("#button").click(function(){
$.ajax({
url: "geo.php",
method: "POST",
data: {
checkAddress: $("#largeText").val()
},
success: function(response){
console.log(response);
//your script
}
})
});

Retrieving data value from database from ajax function

I have a ajax function that would retrieve data from my database and display it in my textbox. I am using a JQuery Form Plugin to shorten the ajax process a little bit. Now what I want to do is to get the data back from the php script that I called from the ajax function.
The form markup is:
<form action="searchFunction.php" method="post" id="searchForm">
<input type="text" name="searchStudent" id="searchStudent" class="searchTextbox" />
<input type="submit" name="Search" id="Search" value="Search" class="searchButton" />
</form>
Server code in searchFunction.php
$cardid = $_POST['searchStudent'] ;
$cardid = mysql_real_escape_string($cardid);
$sql = mysql_query("SELECT * FROM `users` WHERE `card_id` = '$cardid'") or trigger_error(mysql_error().$sql);
$row = mysql_fetch_assoc($sql);
return $row;
The ajax script that processes the php is
$(document).ready(function() {
$('#searchForm').ajaxForm({
dataType: 'json',
success: processSearch
});
});
function processSearch(data) {
alert(data['username']); //Am I doing it right here?
}
In PHP, if I want to call the data, I would just simply create a function for the database and just for example echo $row['username'] it. But how do I do this with ajax? I'm fairly new to this so, please explain the process.
$('#Search').click(function (e) {
e.preventDefault(); // <------------------ stop default behaviour of button
var element = this;
$.ajax({
url: "/<SolutionName>/<MethodName>",
type: "POST",
data: JSON.stringify({ 'Options': someData}),
dataType: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
error: function () {
alert('Unable to load feed, Incorrect path or invalid feed');
},
success: processSearch,
});
});
function processSearch(data) {
var username= ($(data).find('#username'));
}
Change the input type submit to button. Submit will trigger the action in the form so the form will get reloaded. if you are performing an ajax call change it into button.
Everything seems to be fine, except this bit -
function processSearch(data) {
alert(data['username']); //Am I doing it right here?
}
You need to change it to -
function processSearch(data) {
// data is a JSON object. Need to access it with dot notation
alert(data.username);
}
UPDATE
You also need to return a JSON response from your PHP file. Something like -
// Set the Content Type to JSON
header('Content-Type: application/json');
$data = [
"key" => "value"
];
return json_encode($data);
In your case you can directly encode the $row like so -
return json_encode($row);

Enter ID in html form and load related data from MySQL database in same page

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 :-)

Submit form for php without refreshing page

I've search for many solution but without success.
I have a html form;
<form id="objectsForm" method="POST">
<input type="submit" name="objectsButton" id="objectsButton">
</form>
This is used for a menu button.
I'm using jquery to prevent the site from refreshing;
$('#objectsForm').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '/php/objects.php',
data: $('#objectsForm').serialize(),
success: function () {
alert('success');
}
});
});
In my php file I try to echo text to the body of my site;
<?php
if (isset($_POST["objectsButton"])){
echo '<div id="success"><p>objects</p></div>';
} else {
echo '<div id="fail"><p>nope</p></div>';
}
?>
I know the path to my php file is correct, but it doesn't show anything? Not even the "fail div".
Does anyone has a solution for me?
Thanks in advance!
The success function takes two parameters. The first parameter is what is returned from the php file. Try changing it to:
success: function (xhr){ alert(xhr);}
Based in your php source..
$.ajax({
type: 'post',
dataType: "html", // Receive html content
url: '/php/objects.php',
data: $('#objectsForm').serialize(),
success: function (result) {
$('#divResult').html(result);
}
});
PHP scripts run on the server, that means any echo you do won't appear at the user's end.
Instead of echoing the html just echo a json encoded success/ failure flag e.g. 0 or 1.
You'll be able to get that value in your success function and use jQuery to place divs on the web page.
PHP:
<?php
if (isset($_POST["objectsButton"])){
echo json_encode(1); // for success
} else {
echo json_encode(0); // for failure
}
?>
jQuery:
var formData = $('#objectsForm').serializeArray();
formData.push({name:this.name, value:this.value });
$.ajax({
type: 'post',
url: '/php/objects.php',
dataType: 'json',
data: formData,
success: function (response) {
if (response == 1) {
alert('success');
} else {
alert('fail');
}
}
});
EDIT:
To include the button, try using the following (just before the $.ajax block, see above):
formData.push({name:this.name, value:this.value });
Also, have the value attribute for your button:
<input type="submit" name="objectsButton" value="objectsButton" id="objectsButton">

Getting data from form.serializaArray()

i need help..why does my code not working?what is the proper way to get the data from a form.serialize? mines not working.. also am doing it right when passing it to php? also my php code looks awful and does not look like a good oop
html
<form action="" name="frm" id="frm" method="post">
<input type="text" name="title_val" value="" id="title_val"/>
post topic
</form>
<div id="test">
</div>
Javascript
$( document ).ready(function() {
$('#save').click(function() {
var form = $('#frm');
$.ajax({
url: 'topic.php',
type:'get',
data: form.serializeArray(),
success: function(response) {
$('#test').html(response);
}
});
});
});
Php
<?php
class test{
public function test2($val){
return $val;
}
}
$test = new test();
echo $test->test2($_POST['title_val']);
?>
OUTPUT
You're telling your ajax call to send the variables as GET variables, then trying to access them with the $_POST hyperglobal. Change GET to POST:
type:'post',
Also, it should be noted that you are binding your ajax call to the click on your submit button, so your form will still be posting. You should bind on the form's submit function instead and use preventDefault to prevent the form posting.
$('#frm').submit(function(e) {
e.preventDefault(); // stop form processing normally
$.ajax({
url: 'topic.php',
type: 'post',
data: $(this).serializeArray(),
success: function(response) {
$('#test').html(response);
}
});
});

Categories