When I make an AJAX call from a form, it shows it is successful, but the data object is null. The code is as follows:
$.ajax(
{
url: 'shipprocess.php',
dataType: 'json',
type: 'POST',
success: function(data)
{
alert('Data is: ' + data);
alert('The AJAX request was a success.');
},
'error': function()
{
alert('An unexpected error occurred.');
}
});
return false;
The form looks like this:
<div class="processedDate">
<form action="shipprocess.php" method="POST" id="shipProcess2" name="shipProcess2">
<input type="hidden" name="empID" value="1" />
<input type="hidden" name="thisOrderID" id="thisOrderID2" value="2" />
<label>Date Shipped </label>
<input type="text" name="shipDate" id="shipDate2" class="shipDate" size="20" value="" />
<input type="submit" name="shipped" id="shipped2" class="shipped" value="Shipped!" />
</form>
</div>
After the AJAX call is made, Firebug shows the status as 200 and content length as 0. The script that processes the form is called shipprocess.php. It echos the following data when the return: false; line is commented out:
[ { "sd": "2012-09-17", "eid": "1", "oid": "2", "efn": "Johnathan", "eln": "Smith" } ]
For some reason, the script keeps alerting that data is null. A complete example can be found at http://www.yellowcas.com/ship/shipexample.php. This example shows the alert message that the data object is null when you submit the form. I also have a complete example of the data that the shipprocess.php script returns at http://www.yellowcas.com/ship/shipexample1.php. I have used AJAX before to populate the city and state input fields for a zip code that is entered by the user. The jQuery script is almost identical except for the fact that I use GET instead of POST for the zip code form.
I have tried declaring the header in PHP as JSON data, but that doesn't help either. Firebug doesn't seem to be giving me any helpful information either. I have tested the script using a different file called testjson.html. In that file, I put valid JSON data as the only line in the file with no headers at all, and it returns the data variable as an object. That example is at www.yellowcas.com/ship/shipexample2.php. I couldn't post more than 2 hyperlinks. If you would like to see the code for shipprocess.php, I will gladly post it. I just don't want to make this post too long. Any ideas would be greatly appreciated. Thank you.
I decided to post the shipprocess.php code to be sure you can see what I have done.It is as follows:
<?php
require_once('dblogin.php');
require_once('dbconnect.php');
require_once('funcs.php');
$err = array();
$datePattern = "!^(\\d\\d)[-/](\\d\\d)[-/](\\d\\d(?:\\d\\d)?)$!";
$psErr = "Shipping date is required.";
$emErr = "Employee ID is missing.";
$orErr = "Order ID is missing.";
if(isset($_POST['shipped']))
{
$postEID = clean($_POST['empID'],$emErr,$n);
$postOID = clean($_POST['thisOrderID'],$orErr,$n);
$postShipDate = clean($_POST['shipDate'],$psErr,$n);
$now = date("Y-m-d H:i:s");
if($postEID == $emErr)
{
$err[] = $postEID;
}
else
{
$query = "SELECT FK_UserID,FirstName,LastName FROM employees WHERE EmployeeID = '$postEID'";
$res = mysql_query($query);
if(mysql_num_rows($res) < 1)
{
$err[] = "Employee does not exist.";
}
else
{
while($row = mysql_fetch_assoc($res))
{
$retUserID = $row['FK_UserID'];
$retFirstName = $row['FirstName'];
$retLastName = $row['LastName'];
}
}
}
if($postOID == $orErr)
{
$err[] = $postOID;
}
if($postShipDate == $psErr)
{
$err[] = $postShipDate;
}
else
{
if (preg_match($datePattern,$postShipDate,$sMatches))
{
$sMonth = $sMatches[1];
$sDay = $sMatches[2];
$sYear = $sMatches[3];
if(checkdate($sMonth,$sDay,$sYear))
{
$shipDate = "$sYear-$sMonth-$sDay";
}
else
{
$err[] = "Invalid shipping date.";
}
}
else
{
$err[] = "Invalid Shipping Date";
}
}
if(empty($err))
// Keep processing the information if there are no errors.
{
$data[] = "$postEID,$shipDate,$postOID,$now,$retFirstName,$retLastName";
}
else
// Return the errors to the user so corrections can be made.
{
$data[] = implode(",",$err);
}
for ($i=0;$i<sizeof($data);$i++)
{
$info = explode(",",$data[$i]);
$data[$i] = $info;
}
$result = array();
for ($y=0;$y<sizeof($data);$y++)
{
if (($data[$y][0]) !== false)
{
array_push($result, array("sd"=>$data[$y][1], "eid"=>$data[$y][0], "oid" => $data[$y][2], "efn"=>$data[$y][4], "eln"=>$data[$y][5]));
}
if (count($result) > 2)
{
break;
}
}
}
echo array_to_json($result);
?>
Please try out the three example pages I have provided to see what the different results are. Thank you.
Your code lacks at least 2 things:
1: When posting with Ajax, you have to send post data. So you have to tell what data you want to send. Most of the time it will be the serialized form data, but it could be anything.
var dataString = 'name=Gr G';
$.ajax(
{
url: 'shipprocess.php',
dataType: 'json',
data: dataString,
type: 'POST',
...
2: You expect a return value, but you do not send a return value. In shipprocess.php after processing you should echo somethning like this:
...
echo 'data received and processed';
...
You are misusing the $.ajax() method, you have to specify the "data" parameter with the contents of your form.
So you should do something like :
$.ajax({
"url": 'shipprocess.php',
"dataType": 'json',
"type": 'POST',
"data": $("#myform").serialize(),
});
This is what I used to send the data.
var jqXHR = $.ajax({
type: 'POST',
url: your url,
data: { var name: 'data here'},
dataType: 'json'
});
jqXHR.done(function (your returned data) { your stuff )};
Related
So I would like to pass the php array values from this form id to my ajax form. Everything works fine except that it will only display the (1) id number.
Here is my form code: I am passing the $row[topic_id'] as a value to get the id for jquery.
public function forumview($query){
$stmt = $this->db->prepare($query);
$stmt->execute();
$results = $stmt->fetchAll();
if($stmt->rowCount()>0){
foreach($results as $row){
echo '<tr>';
echo '<td style="color: #333;"><span class="pull-right">';
//Problem is here with the $row['topic_id'] portion
if(isset($_SESSION['user_session'])){
echo '<a href="#" class="upVoteArrow"
onclick="upVoteIncrementValue('.$row['topic_id'].');">';
}else{
echo '<a href="#" id="loginForm" class="upVoteArrow" data-
toggle="modal" data-target="#loginModal"><i class="fa fa-arrow-up"></i>
</a>';
}
echo '<span id="voteCount">'.$this->cleanNumber($row['topic_likes']).'</span>';
}
Here is my Ajax call to send the info to my php file
function upVoteIncrementValue(postID){
event.preventDefault();
//var upVoteIncrement = $("#upVoteIncrement").val(); //not needed
$.ajax({
type: "POST",
url: "voting.php",
data: {
"upVoteIncrement": postID,
},
dataType: "json",
cache: false,
success: function(response){
if(response){
var response = $.trim(response);
if(response){
$('#voteCount').html(response);
}
else {
return false;
}
}
}
});
Then here is the php file that handles the call.
if(isset($_POST['upVoteIncrement'])){
$upVoteIncrement = $_POST['upVoteIncrement'];
$stmt = $conn->prepare('UPDATE topics SET topic_likes = topic_likes+1 WHERE topic_id = :id LIMIT 1');
$stmt->bindParam(':id', $upVoteIncrement);
$stmt->execute();
$upVote = $conn->prepare('SELECT topic_likes FROM topics WHERE topic_id = :id LIMIT 1');
$upVote->bindParam(':id', $upVoteIncrement);
$upVote->execute();
$upVoteCount = $upVote->fetchAll();
if($upVote->rowCount() > 0){
foreach($upVoteCount as $row){
$up = $row['topic_likes'];
$results[] = $up;
//exit(); //not needed
}
}
echo json_encode($results);
}
Essentially I am just making a simple up vote system that the user clicks on and it updates the database incrementing by 1. It increments the values and everything works except it will only increment it for the last posted item. So even if I upvote on a topic from earlier it will only add 1 vote to the last inserted topic. Any advice is much appreciated, thanks in advance!
If your using a loop to populate the row id, which it looks like you are here are your problems.
The loop is creating a hidden input element on every iteration of the loop and you are not changing the id of the element. So you will have a bunch of elements all with the same id. That will cause you problems a few different ways.
I changed your PHP code so that each element will have it's own id. I also changed the your javascript function so that the id value is passed to the function itself.
See if this helps:
PHP:
if(isset($_SESSION['user_session'])){
echo '<input type="hidden" id="' . $row['topic_id'] . '" name="upVoteIncrement"
value="' . $row['topic_id'] . '"><a href="#" class="upVoteArrow"
onclick="upVoteIncrementValue(' . $row['topic_id'] . ');">';
}
JS:
function upVoteIncrementValue(postID){
event.preventDefault();
//var upVoteIncrement = $("#upVoteIncrement").val(); //Don't need this anymore.
$.ajax({
type: "POST",
url: "voting.php",
data: {
"upVoteIncrement": postID, //Use the passed value id value in the function.
},
dataType: "html",
cache: false,
success: function(response){
if(response){
var response = $.trim(response);
if(response){
$('#voteCount').html(response);
}
else {
return false;
}
}
}
});
Hope it helps!
I also want to point out that in the code below:
if($upVote->rowCount() > 0){
foreach($upVoteCount as $row){
$up = $row['topic_likes'];
echo $up;
exit();
}
}
You are exiting the script on the first iteration of the loop and you will only ever get one result back.
If you need to return an array of data it should look like this:
if($upVote->rowCount() > 0){
foreach($upVoteCount as $row){
$up = $row['topic_likes'];
$results[] = $up;
//exit();
}
}
echo json_encode($results);
You will then need to set your datatype to json instead of html.
The response in your ajax will now be an array. To see the array:
success: function(response){
if(response){
console.log(response); //Look in your console to see your data.
var response = $.trim(response);
if(response){
$('#voteCount').html(response);
}
else {
return false;
}
}
}
The problem is that in the event handler you addressing element by id, and it's not always the same that you click on.
function upVoteIncrementValue(){
event.preventDefault();
// Always will be last inserted element
var upVoteIncrement = $("#upVoteIncrement").val();
You can use event to get valid element. It's default argument that passed to handler, but remember to define it without braces:
<input onclick="upVoteIncrementValue" />
Then your handler:
function upVoteIncrementValue(event){
event.preventDefault();
var upVoteIncrement = $(event.target).val();
Also if you have several elements with the same ID it's invalid HTML, at least it will hit warning at https://validator.w3.org/ .
So you should set id arg for your element only in case if it's unique, and having this mindset will help you to not hit similar issue again.
Here is my HTML
<input x-webkit-speech id="mike" name="string" style="position: relative;" disabled lang="ru" />
Then when the field is changes,
This function executes
$(document).ready(function(){
$('#mike').bind('webkitspeechchange',function()
{
a= $(this).val();
recognizeAjax(a);
}) ;
});
function recognizeAjax(string) {
var postData ="string="+string;
$.ajax({
type: "POST",
dataType: "json",
data: postData,
beforeSend: function(x) {
if(x && x.overrideMimeType) {
x.overrideMimeType("application/json;charset=UTF-8");
}
},
url: 'restURL.php',
success: function(data) {
// 'data' is a JSON object which we can access directly.
// Evaluate the data.success member and do something appropriate...
if (data.success == true){
alert(data.message);
}
else{
alert(data.message+'hy');
}
}
});
And here is my PHP (please don't say anything about the way i connect to DB it doesn't metter right now)
<?php header('Content-type: application/json; charset=utf-8');
error_reporting(E_ALL);
ini_set('display_errors', true);
// Here's the argument from the client.
$string = $_POST['www'];
$quest=1;
$con=mysql_connect("localhost", "******", "*********") or die(mysql_error());
mysql_select_db("vocabulary", $con) or die(mysql_error());
mysql_set_charset('utf8', $con);
$sql="SELECT * FROM `text` WHERE event_name = 'taxi' AND quest_id = '".$quest."'";
$result = mysql_query($sql);
mysql_close($con);
while($row = mysql_fetch_array($result))
{
if ($string == htmlspecialchars($row['phrase']))
{
$data = array('success'=> true,'message'=>$row['phrase']);
// JSON encode and send back to the server
header("Content-Type: application/json", true);
echo json_encode($data);
exit;
break;
} else {
// Set up associative array
$data = array('success'=> false,'message'=>'aint no sunshine');
header("Content-Type: application/json", true);
echo json_encode($data);
exit;
break;
}
}
When i change the dataType to "text" in the javasript function - i receive an alert with 'undifiend'
But when chenge it to 'json'.. i receive nothing (chrome debuger see nothing)
I set up all encodings to this article http://kunststube.net/frontback/
And i checked it with simple POST requests - it works perfect.
The problem with json.
Any suggestions?
Thanks
Just remove the datatype="json" bit and change the data bit to data: { "string": string }
After that try a print_r(json_decode($_POST['string']));. I'm quite sure that will get you your data.
And indeed remove your beforeSend callback.
I think the prob is the code var postData ="string="+string;
jQuery expects this to be a proper JSON Object.
Next: $string = $_POST['www']; takes a parameter named "www" from your post request, but the name above is "string" (at least).
Try either (!) this:
var getData ="www="+string;
$.ajax({
type: "POST",
dataType: "json",
data: null,
beforeSend: function(x) {
if(x && x.overrideMimeType) {
x.overrideMimeType("application/json;charset=UTF-8");
}
},
url: 'restURL.php?' + getData,
and server:
$string = $_GET['www'];
or this (php)
$string = $_POST['string'];
$stringData = json_decode($string);
// catch any errors ....
$quest=$stringData[....whatever index that is...];
I am developing ajax Based Search , This is demo of how it will be. I am faceing Problem in returning result. I need to show the Result 2 times. But its only showing once. Below is my HTML code
<form action="" method="post" id="demoform">
<select style="width:250px;padding:5px 0px;color:#f1eedb;" name="product" class="product">
<option>TENNIS</option>
<option>FOOTBALL</option>
<option>SWIMMING</option>
</select>
</form>
<div id="result">Display Result Here</div>
I Using The Below Ajax Script to Retrieve Data :-
$(".product").change(function(){
$.ajax({
type : 'POST',
url : 'post.php',
dataType : 'json',
data: {
product : $(".product option:selected").text(),
},
success : function(data){
$('#result').removeClass().addClass((data.error === true) ? 'error' : 'success')
.html(data.msg).show();
if (data.error === true)
$('#demoForm').show();
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
$('#result').removeClass().addClass('error')
.text('There was an error.').show(500);
$('#demoForm').show();
}
});
});
The post.php file has the following code :-
<?php
require('connect.php');
$get_select = $_POST[product];
if($get_product!='FOOTBALL'){
$return['error'] = true;
return['msg'] = 'Incorrect Selection';
echo json_encode(return);
}
else {
$return['error'] = false;
$i=0;
while($i<2) {
return['msg'] = $get_product;
}
echo json_encode(return);//Returns only one result.
}
?>
I need to show the result Two times as "CRICKET CRICKET", but its only showing once.
What should i do to get both the result.
Is it possible that this line is confusing php:
while($i<2) {
return['msg'] = $get_product;
}
Should it be $return? Using a reserved word like 'return' is a tad iffy too.
Please change the following code:
else {
$i=0;
$messageToReturn = "";
while($i<2) {
$messageToReturn .= $get_product; //Append to your variable
}
return json_encode($messageToReturn); //Returns the result
}
I would suggest to change the while to a for loop.
In that case you will get this:
else {
$messageToReturn = "";
for($i = 0; $i < 2; $i++)
{
$messageToReturn .= $get_product; //Append to your variable
}
return json_encode($messageToReturn);
If you know the times you need to repeat, use a for loop. The while is never ending. So you can get a possible stack overflow...
I am getting a NaN error in my ajax callback function and can only think it has to do with an array in PHP. I have been trying to find ways to correct it but have come up against a brick wall.
What is supposed to happen is that PHP queries the database and if there are no results send a response to ajax and issue the error message. However, all I am getting is NaN. The error stems from the success code below.
I would be grateful if someone could point out my error.
PHP code:
$duplicates = array();
foreach ($boxnumber as $val) {
if ($val != "") {
mysql_select_db($database_logistor, $logistor);
$sql = "SELECT custref FROM boxes WHERE custref='$val' and status = 'In'";
$qry = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($qry) < 1) {
$duplicates[] = '[ ' . $val . ' ]';
$flag = 1;
} else {
$duplicates[] = $val;
}
}
}
//response array with status code and message
$response_array = array();
if (!empty($duplicates)) {
if ($flag == 1) {
//set the response
$response_array['status'] = 'error';
$response_array['message'] = 'ERROR: ' . implode(',', $duplicates) . ' needs to be in the database to be retrived.';
}
//if no errors
} else {
//set the response
$response_array['status'] = 'success';
$response_array['message'] = 'All items retrieved successfully';
$response_array['info'] = ' You retrieved a total of: ' . $boxcount . ' boxes';
}
//send the response back
echo json_encode($response_array);
Relevant ajax:
$("#brtv-result").html(msg.message+msg.info);
jQuery code:
$(function() {
$("#BRV_brtrv").submit(function() {
var send = $(this).serialize();
$.ajax({
type: "POST",
url: "boxrtrv.php",
cache: false,
data: send,
dataType: "json",
success: function(msg) {
if( msg.status === 'error') {
$("#brtv-result").fadeIn(1000).delay(1000).fadeOut(1000);
$("#brtv-result").removeClass('error');
$("#brtv-result").removeClass('success');
$("#brtv-result").addClass(msg.status);
$("#brtv-result").html(msg.message);
}
else {
$("#brtv-result").fadeIn(2000).delay(2000).fadeOut(2000);
$("#brtv-result").removeClass('error');
$("#brtv-result").addClass('success');
$("#brtv-result").addClass(msg.status);
$("#brtv-result").html(msg.message+msg.info);
//location.reload(true);
//$('#brtv-result').addClass("result_msg").html("You have successfully retrieved: "+data.boxnumber).show(1000).delay(4000).fadeOut(4000);
$("#BRV-brtrv-slider").val(0).slider("refresh");
$("input[type='radio']").attr("checked",false).checkboxradio("refresh");
var myselect = $("select#BRV-brtrv-department");
myselect[0].selectedIndex = 0;
myselect.selectmenu("refresh");
var myselect = $("select#BRV-brtrv-address");
myselect[0].selectedIndex = 0;
myselect.selectmenu("refresh");
}
},
error:function(){
$("#brtv-result").show();
$("#brtv-result").removeClass('success');
$("#brtv-result").addClass('error');
$("#brtv-result").html("There was an error submitting the form. Please try again.");
}
});
return false;
});
});
NaN (pronounced nan, rhymes with man) only happens when you try to do an operation which requires a number operand. For example, when you try to Number('man') you'll get this error.
What you return from your PHP file, is simply an array which contains simply data. So, the problem is in your JavaScript. You have to send more parts of your JavaScript, so that we can see it thoroughly.
However, I recommend that you use Firebug and set a breakpint at the correct place (the callback function start), and check the stack trace of the calls to diagnose the problem.
I'm just trying to spit the elements of an array into seperate input fields on a form via jquery's AJAX.
Heres my javascript code:
$('#based').change(function() {
if ($(this).val().length > 0)
{
$.ajax({
type: "POST",
url: "ajax.php",
data: "id="+$(this).val(),
success: function(data){
if (data != 'error')
{
$('#keyword').val(data[2]);
$('#keyword_slug').val(data[3]);
}
}
});
}
});
Heres my PHP code for 'ajax.php':
$sql = mysql_query("select * from `keywords` where `id`='".mysql_real_escape_string($_POST['id'])."'");
if (mysql_num_rows($sql) == 0)
{
echo 'error';
}
else
{
while ($row = mysql_fetch_assoc($sql))
{
foreach ($row as $k => $v)
$data[] = $v;
}
echo json_encode($data);
}
Its not working. What do I do here? I've looked into serializeArray but can't get anything to work properly.
I think you need dataType: 'json' if you are expecting JSON back.
Otherwise jQuery has to guess, and if you are not sending the Content Type application/json, it may guess wrong.