Why is this jQuery ajax failing? - php

I'm trying to do some really basic AJAX using PHP & jQuery, but for some reason when I enter text into the input field and click the button I'm always getting null data back. What am I doing wrong?
WebService.php:
<?php
$return['ReturnString'] = $_POST['SearchString'];
for ($i = 1; $i < 100; $i++)
{
$return['ReturnString'] = $return['ReturnString'] . $_POST['SearchString'];
}
return json_encode($return);
?>
HTML:
<html>
<head>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("jquery", "1");
</script>
<script type="text/javascript" src="Scripts/script.js"></script>
</head>
<body>
<form>
<div>
<input type="text" id="txtJavaPHP" />
<input type="button" id="btnJavaPHP" value="Go" />
<br />
<br />
<span id="spanJavaPHP"></span>
</div>
</form>
</body>
</html>
Script.js:
$(document).ready(SetupButtonClicks);
function SetupButtonClicks() {$('#btnJavaPHP').click(DoPHP);}
function DoPHP() {
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: 'WebService.php',
dataType: 'json',
data: {
SearchString: $('#txtJavaPHP').val()
},
success: function (data) {
if (data == null)
$('#spanJavaPHP').text("Data is null");
else
$('#spanJavaPHP').text(data.ReturnString);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
$('#spanJavaPHP').text('There was an error: ' + errorThrown);
}
});
return false;
}

I think the problem lies here, but I have not used AJAX for a while, so I was not able to fully go through the AJAX Code:
echo $return['ReturnString'];
return json_encode($return);
You should be echoing the json_encode($return);
echo json_encode($return);
This should hopefully fix it. Although I do not know why you are looping that data 100 times...but yea.

Related

cannot get value from php ajax

Cannot get value from php true AJAX.
My php code is
<?php
$name = $_POST['name'];
$hobby = $_POST['hobby'];
if (!empty($name and $hobby)){
echo 'Data was succesfully captured';
}else {
echo 'Data was not captured'
}
my html code is
<div id="result"></div>
<form method="post">
<input name="name" type="text" id="name">
<br>
<input name="hobby" type="text" id="hobby">
<input name="snd_btn" type="button" id="snd_btn" value="Save">
</form>
JS
$(document).ready(function(){
$('#snd_btn').click(function() {
var name = $('#name').val();
var hobby = $('#hobby').val();
$.ajax({
url: "save.php",
type: "POST",
dataType: 'json',
data: { name, hobby,
success: function(result) {
$('#result').html(result);
},
}
});
});
});
if i Change in js to
success: function() {
$('#result').html('Data was succesfully captured');
},
it work but not from php
This one is wrong.
if (!empty($name and $hobby)) {
Please replace that with:
if (!empty($name) and !empty($hobby)) {
You have to check for emptiness of the variable for each one.
Problems:
After hobby comes a "}" before ",".
Then, you have an error-prone additional "}". The one after the closing "}," (btw, delete the ",") of success callback.
You forgot the semicolon at the end of the line echo 'Data was not captured'.
The ajax call expects a JSON encoded response, as you defined dataType: JSON. So, in PHP, you must encode the response string - with json_encode.
Since you don't have an error callback (error: function(...){...}) you can't see any errors. So, define one. An example is below.
Recommendations:
Define the data object as below.
The PHP check on empty values should happen as below.
You must also check if the posted values are set.
Don't show any specific error details to the users. Just display a general user-friendly message to them. So, don't do as I did - by printing the error details in the console :-)
index.php:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes" />
<meta charset="UTF-8" />
<!-- The above 3 meta tags must come first in the head -->
<title></title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#snd_btn').click(function () {
var name = $('#name').val();
var hobby = $('#hobby').val();
$.ajax({
method: 'POST',
dataType: 'json',
url: 'save.php',
data: {
'name': name,
'hobby': hobby
},
success: function (result, textStatus, jqXHR) {
$('#result').html(result);
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error! See the console');
console.log(textStatus);
console.log(errorThrown);
console.log(jqXHR);
},
complete: function (jqXHR, textStatus) {
//...
}
});
});
});
</script>
</head>
<body>
<div id="result"></div>
<form method="post">
<input name="name" type="text" id="name">
<br>
<input name="hobby" type="text" id="hobby">
<input name="snd_btn" type="button" id="snd_btn" value="Save">
</form>
</body>
</html>
save.php:
<?php
/*
* Check if the values are set.
* I used here the short "null coalescing operator".
* Search for it in the link below.
*
* #link https://secure.php.net/manual/en/language.operators.comparison.php Comparison Operators.
*/
$name = $_POST['name'] ?? '';
$hobby = $_POST['hobby'] ?? '';
if (!empty($name) && !empty($hobby)) {
$response = 'Data was succesfully captured';
} else {
$response = 'Data was not captured';
}
echo json_encode($response);
First of all you have check that the ajax call will be successfully done or not
If ajax call was successfully done then,
Check the response of success data by print the in console.
Your php code should be like this
<?php
$name = $_POST['name'];
$hobby = $_POST['hobby'];
if ($name and $hobby ){
echo json_encode('Data was succesfully captured');
}else {
echo json_encode('Data was not captured');
}
From php you have to return data in form of json.
And js side:
$(document).ready(function(){
$('#snd_btn').click(function() {
var name = $('#name').val();
var hobby = $('#hobby').val();
$.ajax({
url: "save.php",
type: "POST",
dataType: 'json',
data: { name:name, hobby:hobby} // data in { key : value}
success: function(result) {
res = JSON.parse(res);
console.log(res);// display in developertools > console
$('#result').html(res);
},
}); }); });

Post data with ajax or ajax(json) to php in same page

I'm trying message application. My goal is get sender id and receiver id with a click on one button.
After then post this datas with ajax or ajax(json) to php in same page.
I will use the incoming data in php with mysql_query. I tryed many examples. But never get result. My example code at below.
Little Note: Success alert comes but doesn't print any data on screen.
<html>
<head>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
</head>
<body>
<button type="button" onclick="myFunc()">Get ID</button>
<script>
function myFunc()
{
var id = 'example';
jQuery.ajax({
url:'index.php',
type: "POST",
data: {'name':id},
success: function(data)
{
alert("success");
}
});
};
</script>
<?php
if(isset($_POST['name']))
{
$value = $_POST['name'];
echo $value;
}
else
{
echo "don't work.";
}
?>
</body>
</html>
<?php
if(isset($_POST['name']))
{
echo json_encode(array(
'value' => $_POST['name']
));
exit();
}
?>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
</head>
<body>
<button type="button" onclick="myFunc()">Get ID</button>
<script>
function myFunc()
{
var id = 'example';
jQuery.ajax({
url:'index.php',
type: "POST",
data: {'name':id},
dataType : 'json',
success: function(data)
{
alert("success");
}
});
};
</script>
</body>
</html>

how to asynchronously get data using ajax and php

i am new in ajax. i want to display the text entered inside the input to another div element.here is the image given below:
here is my code :
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
<label for="bar">Enter Text</label>
<input id="bar" name="bar" type="text" value="" />
<!-- The result of the search will be rendered inside this div -->
<div id="result">Text Output: </div>
<script >
/* Get from elements values */
var values = $(this).serialize();
$.ajax({
url: "testajax.php",
type: "post",
async:true,
data: values ,
success: function (response) {
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
</script>
</body>
</html>
here is php code:
<?php
$bar = $_POST['bar']
?>
please help me to fix the problem & also minimize the code if possible.thanks
Client-side
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
<form>
<label for="bar">Enter Text</label>
<input id="bar" name="bar" type="text" value="" />
<input type="submit" value="Go">
</form>
<!-- The result of the search will be rendered inside this div -->
<div id="result">Text Output: </div>
<!-- For testing purposes comes here the JSON object (stringified) -->
<div id="jsonstring" style="font-family:monospace;">Json object</div>
<script type="text/javascript">
var values = $("form").serialize();
$("form").on("submit", function( event ) {
event.preventDefault();
var values = $( this ).serialize();
$.ajax({
url: "testajax.php",
type: "post",
async: true,
data: values,
dataType: 'json',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
success: function(json) {
$('#result').html((json.content) ? (json.content) : '???');
$('#result').prop('title', json.title);
$('#jsonstring').html('Json object: '+JSON.stringify(json));
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
});
</script>
</body>
</html>
Server-side
<?php
$bar = (isset($_POST['bar'])) ? $_POST['bar'] : '';
$result = array(
'title' => 'This is the result from an AJAX call',
'content' => 'This is the result: <span style="color:red;">' . $bar . '</span>',
);
echo json_encode($result);
?>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
<form name="form">
<label for="bar">Enter Text</label>
<input id="bar" name="bar" type="text" value="" />
<input type="submit" id="submit" value="click" >
</form>
<!-- The result of the search will be rendered inside this div -->
<div id="result">Text Output: </div>
<script >
/* Get from elements values */
$("#submit").on("click", function(){
var values = $(this).serialize();
$.ajax({
url: "testajax.php",
type: "post",
async:true,
data: values ,
success: function (response) {
$('#result').html((response);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
});
</script>
</body>
</html>

jQuery.ajax - Duplicate Content After Posting Data Back To The Same Page

Problem 1: My content overlaps itself twice after I post some data back to the same page using jQuery.ajax(). The reason why I'm posting data back to the same page is because I need to pass my JavaScript values to the PHP side.
Question: How do I edit my code such that there will only be 1 copy of my content, before and after posting of data to the same page?
Problem 2: You may have noticed there is a $("#test").html(data); in my bingo function and a <span id="test"></span> in my body. I can't seem to remove them if not the passing of Javascript values to the PHP side would not work as shown by my print_r().
Question: Is there any way I can remove them but still pass my values from JavaScript to PHP using jQuery.ajax()?
bingo.php
<html>
<head>
<script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
<?php
if (!isset($_POST['varA']) && !isset($_POST['varB']))
{
?>
<script type="text/javascript">
$(document).ready(bingo);
function bingo()
{
jQuery.ajax({
type: "POST",
data: {varA: "123", varB: "456"},
success: function(data)
{
alert("POST to self is successful!");
$("#test").html(data);
}
});
}
</script>
<?php
}
else
{
print_r($_POST['varA']);
echo " - ";
print_r($_POST['varB']);
}
?>
</head>
<body>
<input type="text" value="meow"/>
<span id="test"></span>
</body>
</html>
Omg that is so messy! Try the following code anyway:
<?php
if (isset($_POST['varA']) && isset($_POST['varB'])) {
print_r($_POST['varA']);
echo " - ";
print_r($_POST['varB']);
} else {
?>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(bingo);
function bingo()
{
jQuery.ajax({
type: "POST",
data: {varA: "123", varB: "456", ajax: true},
success: function(data)
{
alert("POST to self is successful!");
$("#test").html(data);
}
});
}
</script>
</head>
<body>
<input type="text" value="meow"/>
<span id="test"></span>
</body>
</html>
<?php
}
?>
If you wish to keep your ! in your conditions, you can do it the other way round also.
<?php
if (!isset($_POST['varA']) && !isset($_POST['varB'])) {
?>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(bingo);
function bingo()
{
jQuery.ajax({
type: "POST",
data: {varA: "123", varB: "456"},
success: function(data)
{
alert("POST to self is successful!");
$("#test").html(data);
}
});
}
</script>
</head>
<body>
<input type="text" value="meow"/>
<span id="test"></span>
</body>
</html>
<?php
}
else {
print_r($_POST['varA']);
echo " - ";
print_r($_POST['varB']);
}
?>

Using jQuery's .get() to retrieve PHP data

I'm using jQuery's .ajax() to post to a PHP file called process.php. Process.php has a lot of code in it, but for simplicity's sake, let's just say it contains <?php echo 'hello'; ?>.
Is this the proper jQuery to insert process.php's results into div.results? :
$.get('process.php', function(data) {
$('.results').html(data);
});
So far it doesn't seem to be working.
Here's the HTML/Javascript file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.5.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("form#form").submit(function() {
var username = $('#username').attr('value');
$.ajax({
type: 'POST',
url: 'process.php',
data: 'username=' + username,
success: function() {
$('form#form').hide(function() {
$.get('process.php', function(data) {
$('.results').html(data);
});
});
}
});
return false;
});
});
</script>
</head>
<body id="body">
<form id="form" method="post">
<p>Your username: <input type="text" value="" name="username" id="username" /></p>
<input type="submit" id="submit" value="Submit" />
</form>
<div class="results"></div>
</body>
</html>
Here's process.php (greatly simplified):
<?php
/* get info from ajax post */
$username = htmlspecialchars(trim($_POST['username']));
echo $username;
?>
If you simply want to place the resulting string back into an element, use load().
$('.results').load('process.php');
However, looking at your code...
$.ajax({
type: 'POST',
url: 'process.php',
data: 'username=' + username,
success: function() {
$('form#form').hide(function() {
$.get('process.php', function(data) {
$('.results').html(data);
});
});
}
});
...shows you have misunderstood something. The correct anonymous function to assign to the success callback would be...
function(data) {
$('form#form').hide()
$('.results').html(data);
}
You could try something like this.
function ajax_login() {
if ($("#username").val()) {
$.post("/process.php", { username : $("#username").val() }, function(data) {
if (data.length) {
$("#login_form").hide();
$("#login_result").html(data);
}
})
} else {
$("#login_result").hide();
}
Then in process.php just echo out some text if the post sucesses.
process.php =>
if (isset($_POST['username'])
{
echo 'hello '.$_POST['username'];
}

Categories