Array not acting as expected in jQuery - javascript

I'm doing jQuery Ajax with PHP, and after jQuery passes some $_POST data to PHP, PHP validates those data, and prepares an array with all the errors, and once all validation is done, the count of error is found, and if it is greater than 0, the array is encoded in json and it is printed on the screen. jQuery then grabs those data with 'success:' and it does it, but it doesn't act as expected.
PHP file validating:
<?php
$messages = array();
if(isset($_POST['name']) && isset($_POST['email']) && isset($_POST['subject']) && isset($_POST['message'])) {
if(empty($_POST['name'])) {
$messages[] = "Please fill in the Name field.";
}
if(empty($_POST['email'])) {
$messages[] = "Please fill in the Email field.";
}
if(empty($_POST['subject'])) {
$messages[] = "Please fill in the Subject field.";
}
if(empty($POST['message'])) {
$messages[] = "Please write your message in the Message field!";
}
if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$messages[] = "Invalid email entered!";
}
if(strlen($_POST['name']) > 30 || strlen($_POST['name']) < 3) {
$messages[] = "Your name cannot be less than 3 characters or more than 30 characters.";
}
if(strlen($_POST['email']) > 30 || strlen($_POST['email']) < 3) {
$messages[] = "Your email cannot be less than 3 characters or more than 30 characters.";
}
if(strlen($_POST['subject']) > 30 || strlen($_POST['subject']) < 3) {
$messages[] = "The subject cannot be less than 3 characters or more than 30 characters.";
}
if(strlen($_POST['message']) > 2000 || strlen($_POST['message']) < 40) {
$messages[] = "Your message cannot be less than 40 characters or more than 2000 characters.";
}
if(count($messages) > 0) {
$messages['elements'] = count($messages);
echo json_encode($messages);
} else {
}
}
jQuery code:
$(document).ready( function() {
$(document).on('click', '.contact_submit', function() {
var name = $('input#name').val();
var email = $('input#email').val();
var subject = $('input#subject').val();
var message = $('input#message').val();
var Data = "name=" + name + "&email=" + email + "&subject=" + subject + "&message=" + message;
$.ajax({
type: "POST",
url: "portal/_inc/frontend/form.php",
data: Data,
success: function(messages) {
var Count = messages.length;
$('.messages').empty();
for(var i = 0; i < Count; i++) {
$('.messages').append('<li class"error">' + messages[i] + '</li>\n');
}
}
});
return false;
});
});
All works fine, but my output is in 'char' format like one character at a time. Click here for a screen shot.

It's because your response is a string, and you're iterating over a string.
This PHP code:
echo json_encode($messages);
encodes an object/array into a JSON string.
And this JS code:
var Count = messages.length;
will just return the length of the whole string, not the number of individual objects within the returned JSON.
The simplest way to fix it is to parse the JSON in your success callback:
var messageObject = JSON.parse(messages);
and now the variable messageObject will have the data in the format you expected.

Add dataType:'JSON' to your ajax request:
$.ajax({
dataType:'JSON',
type: "POST",
url: "portal/_inc/frontend/form.php",
data: Data,
.....
and add
header('Content-type: application/json; charset=utf-8');
to your php so that the javascript knows how to handle the response
EDIT
the problem is that the json response is an object, not array, which does not have a .length property.
you'd be better to do it like this:
success: function(messages) {
$('.messages').empty();
$.each(messages,function(){
$('.messages').append('<li class"error">' + this + '</li>\n');
});
}

Related

cant get concat values and php not working

So my problem is that why jquery concat is not working and also it is not posting and can't inserted into the database
I tried changing the code and read references still cant get enough
This is my jquery
var uid = $('#lname').val() + $('fname').val() + $('#datecreated').val(moment().format('YYYY'));
var datecreated = $('#datecreated').val(moment().format('YYYY'));
var fname = $('#fname').val();
var lname = $('#lname').val();
var email = $('#email').val();
var password = $('#pass').val();
var passcheck = false;
This is my ajax
if (uid && fname && lname && email && password && datecreated)
{
var form = $(this);
var formData = new FormData(this);
$(".formcontent").hide();
$.ajax({
url : form.attr('action'),
type: form.attr('method'),
data: form.serialize(),
data: formData,
dataType: 'json',
cache: false,
contentType: false,
processData: false,
success:function(response)
{
this is my full code php, I dunno if the problem is with xampp or not. Im tackling this problem for 3 day straight now and I dunno where the problem is
valid['success'] = array('success' => true, 'messages' => array());
$uid = $_POST ['uid'];
$pass = $_POST['pass'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$datecreated = $_POST['datecreated'];
if ($_POST)
{
if(true)
{
$sqlmail = "SELECT * FROM acc WHERE (email = '$email') AND acc_stat < 3";
$resmail = $connect->query($sqlmail);
if($resmail->num_rows > 0)
{
while($row = $resmail->fetch_array())
{
if($email === $row['email'])
{
$valid['messages'] = "Email address is already taken";
}
}
$valid['success'] = false;
$connect->close();
echo json_encode($valid);
}
else
{
$sql = "INSERT INTO 'acc' ('uid', 'password', 'lname', 'fname', 'email', 'acc_type', 'acc_stat','date_create') VALUES ('$uid', '$pass', '$fname', '$lname', '$email', '3', '1','$datecreated')";
if($connect->query($sql) === TRUE)
{
$valid['success'] = true;
$valid['messages'] = "Account registration successful.";
$connect->close();
echo json_encode($valid);
}
else
{
$valid['success'] = false;
$valid['messages'] = "Network connection not stable. Please try again later.";
$connect->close();
echo json_encode($valid);
}
}
}
else
{
$valid['success'] = false;
$valid['messages'] = "No internet connection.";
$connect->close();
echo json_encode($valid);
}
}
There is a small mistake in your code, please fix it and it should work fine. the error is at line
var uid = $('#lname').val() + $('fname').val() + $('#datecreated').val(moment().format('YYYY'));
chage it to var uid = $('#lname').val() + $('#fname').val() + $('#datecreated').val(moment().format('YYYY'));.
silly mistake of missing just #. one more thing, you will not receive the uid paramter in php side, just because you are not sending it with form. append it to FormData as give,
var uid = $('#lname').val() + $('#fname').val() + $('#datecreated').val(moment().format('YYYY'));.
var formData = new FormData(this);
formData.append('uid' , uid);
Now you will be able to recieve that uid parameter.
Try to use this:
var uid = $('#lname').val() + $('#fname').val() + $('#datecreated').val(moment().format('YYYY'));
var datecreated = $('#datecreated').val(moment().format('YYYY'));
var fname = $('#fname').val();
var lname = $('#lname').val();
var email = $('#email').val();
var password = $('#pass').val();
var passcheck = false;

display data js from datebase sql [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I would like to push my value of textbox to sql and then display it.
I read a lot topics but still nothing. I have always problem to explain my problems but I hope u will see what i want to do escpecialy when u look at db2.php
$("#send").click(function(){
var username = "<span class ='username' = >Klient: </span>";
var newMessage = $("#textbox").val();
nw = newMessage;
$.ajax({
type: "POST",
url: "db2.php",
data: {'name': nw },
success: function (json) {
jss = json.PYT;
oss = json.ODP;
console.log(jss);
}
});
$("#textbox").val("");
var prevState = $("#container").html();
if( prevState.length > 3){
prevState = prevState + "<br>";
}
$("#container").html(prevState + username + newMessage);
$("#container").scrollTop($("#container").prop("scrollHeight"));
ai(newMessage);
});
and my db2.php .
<?php
header('Content-type: application/json');
include 'connect.php';
if (isset($_POST['name'])) {
$name = $_POST['name'];
$queryResult = $connect->query("select * from Chatbot where '$name' LIKE
CONCAT('%',PYT,'%')");
$result = array();
while($pomoc = $queryResult->fetch_assoc()){
$result[] = $pomoc;
}
}
echo json_encode($result);
Now my result is {}, echo is null.
console.log(nw)
VM289:1 dsasa
undefined
I know how to get just output from ajax but if i want to push this data everything goes wrong. Best regards
UPDATE. Now I would like to get jss value out of this function to the other one.
var jss = {}; //(first line code)
$("#send").click(function(){
var username = "<span class ='username' = >Klient: </span>";
var newMessage = $("#textbox").val();
nw = newMessage;
$.ajax({
type: 'POST',
url: 'db2.php',
data: {
'name': nw,
},
success: function(data){
jss = data[0].PYT;
}
});
UPDATE 2
var jss2 = {};
var nw;
$(function(){
username();
$("#textbox").keypress(function(event){
if ( event.which == 13) {
if ( $("#enter").prop("checked") ){
$("#send").click();
event.preventDefault();
}
}
});
$("#send").click(function(){
var username = "<span class ='username' = >Klient: </span>";
var newMessage = $("#textbox").val();
$("#textbox").val("");
var prevState = $("#container").html();
if( prevState.length > 3){
prevState = prevState + "<br>";
}
$("#container").html(prevState + username + newMessage);
$("#container").scrollTop($("#container").prop("scrollHeight"));
ai(newMessage);
});
})
function send_message(message){
var prevState = $("#container").html();
if(prevState.length > 3){
prevState = prevState + "<br>";
}
$("#container").html(prevState + "<span class = 'bot'>Chatbot: </span>" + message);
}
function username(){
$("#container").html("<span class = 'bot'>Chatbot: </span>Hi!");
}
function myFunction() {
var x = document.getElementById("textbox").value;
}
function ai(message){
var jss;
message = message.toLowerCase();
nw = message;
$.ajax({
type: 'POST',
url: 'db2.php',
data: {
'name': nw,
},
success: function(data){
jss = data[0].PYT;
}
});
console.log(jss);
if ((message.indexOf(jss)>=0) || (message.indexOf("?")>=0)){
send_message(Answer);
return;
}
else{
send_message("Nope ");
}
}
I think this is what you need to do with your function so that you can use the jss variable properly, once the ajax request has completed:
function ai(message){
var jss;
message = message.toLowerCase();
nw = message;
$.ajax({
type: 'POST',
url: 'db2.php',
data: {
'name': nw,
},
success: function(data){
jss = data[0].PYT;
console.log(jss);
if ((message.indexOf(jss)>=0) || (message.indexOf("?")>=0)){
send_message(Answer);
return;
}
else{
send_message("Nope ");
}
}
});
}
Any code which relies on the jss variable must not be executed until after the ajax call has completed. Since ajax calls run asynchronously, the only way to guarantee this is for that code to be included in (or triggered from) the "success" callback function in your ajax request.

Adding PHP to script causes rest of JS functions to stop working

<script>
var array = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
<?php
$seatsArray = array();
$myFile = fopen("seats.txt", "w") or die("Unable to Open File!");
if(filesize("seats.txt") == 0) {
for($x = 0; $x < 10; $x++) {
fwrite($myFile, "0\n");
}
}
$seatsArray = file("seats.txt", FILE_IGNORE_NEW_LINES);
fclose($myFile);
print_r($seatsArray);
?>
function checkNumber() {
var number = document.getElementById("userInput").value;
if(number == 1) {
firstClass();
}
else if(number == 2) {
economyClass();
}
else {
document.getElementById("message").innerHTML = "Please enter either 1 or 2.";
}
}
function firstClass() {
for(var x = 0; x <= 4; x++) {
if(array[x] == 0) {
array[x] = 1;
document.getElementById("message").innerHTML = "You have been assigned seat #" + (x+1) + " in first class.";
document.getElementById("f" + (x+1)).style.color = "red";
document.getElementById("userInput").value = "";
break;
}
else if(array[4] == 1) {
document.getElementById("frow").style.color = "red";
if(array[9] == 1) {
document.getElementById("message").innerHTML = "Sorry, the flight is fully booked. The next flight is in three hours.";
}
else {
var confirmation = window.confirm("First class is fully booked, would you like a seat in economy?");
if(confirmation) {
economyClass();
break;
}
else {
document.getElementById("message").innerHTML = "The next flight is in three hours.";
break;
}
}
}
}
}
function economyClass() {
//ETC ETC
</script>
I'm trying to move the array to a text file so it keeps its values after closing but as soon as I add the PHP code underneath all my other functions stop working. The PHP code itself works, creating the seats file and populating it, but everything afterwards doesn't.
for school
Can you show us the content of print_r($seatsArray);
I'm sure this, make an JS error, and everything else in JS stop working.
you shoul use the angular $http service to use your php if you really need it:
$http({
method: "POST",
url: "YOUR.php",
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
You can't just print_r(file()) - PHP-style array causes JS error.
If you want to display contents of this file, you should do it, according to enter link description here line by line
foreach ($lines as $line_num => $line) {
echo htmlspecialchars($line);
}

Convert multiple alerts to one alert

I'm using javascipt to validate a form and the code is like below,
function validateForm() {
console.log("start check form");
var errors = [];
var form = document.getElementsByTagName('form')[0];
/*
* Store appropriate form elements.
* There are many ways to do this, but I'm keeping it
* simple for the example
*/
var fnElem = document.getElementById("name");
var lnElem = document.getElementById("phone");
var firstName = fnElem.value;
var lastName = lnElem.value;
// etc...
// validate required fields
if (firstName === "") {
errors.push({
elem: firstName,
message: "name can't be blank"
});
}
if (lastName === "") {
errors.push({
elem: lastName,
message: "phone can't be blank"
});
}
for(var i=0; i<errors.length;i++){
alert(errors[i].message);
}
return false;
}
and in the for loop it will alert lots of times in the windows.
how can I combine all the alert into one single message..and only alert once.
I know that I can define a string and append one by one, But that seems so fool.
Is there a better way to do this.
First you map the error array to the contained messages: array.map().
Then you can join the messages: array.join().
if (errors.length) {
alert("Errors:\n" + errors.map(function (e) { return e.message; }).join('\n'));
}
Change your loop to append the message to a variable, then alert after the loop:
var messages = "";
for(var i=0; i<errors.length;i++){
messages += errors[i].message + "\n";
}
alert(messages)
for( var sAlert = '', i = 0, iL = errors.length; i < iL; ++i ) {
sAlert += errors[i].message + '\n';
}
alert(sAlert );
I didn't had a closer look at your code but if everything is fine this should solve it :)

PHP json_encode() function not properly read by jquery [duplicate]

This question already has answers here:
How to parse JSON data with jQuery / JavaScript?
(11 answers)
Closed 8 years ago.
I have the following problem,
I'm sending a json_encoded data array from PHP to javascript. The actual JSON I'm receiving from PHP is shown below,
{
"route": "1(M)A",
"startSignal": "AN1",
"startX": 100,
"startY": 320,
"direction": "down",
"endSignal": "AN3",
"endX": 1100,
"endY": 320,
"1AT": {
"length": "100",
"xStart": 100,
"yStart": 320,
"xFinish": 133.33333333333,
"yFinish": 320
},
"1BT": {
"length": "100",
"xStart": 133.33333333333,
"yStart": 320,
"xFinish": 166.66666666667,
"yFinish": 320
},
"1CT": {
"length": "100",
"xStart": 166.66666666667,
"yStart": 320,
"xFinish": 200,
"yFinish": 320
},
"1DT": {
"length": "100",
"xStart": 200,
"yStart": 320,
"xFinish": 233.33333333333,
"yFinish": 320
}
}
In my .JS file, I'm getting the "echo json_encode($dataArray)" as follows,
$.ajax({
url: "visualiser/visualiser_RouteList.php",
data: "JSON",
async: false,
success: function(data){
console.log(data);
}
});
The problem is that for some reason ajax reads the json in the following manner..(every character in JSON is stored as an array element.. so I can't retrieve a particular value of an associated name for example, getting "1(M)A" String value from associated name "route"..
data[0] = "{"
data[1] = " \" "
data[2] = "r"
data[3] = "o"
where am I going wrong?
============================================================================
further edit after receiving the comments,
Thanks everyone, I did change the data to 'dataType = "json"' but it still doesn't work..I really wanted to see [object, object....] when I do 'console.log(data) but nothing is printing out so there must be something wrong with my $array in the PHP source, not sure if anyone's willing do have look but I'm posting my php source here..(Sorry for being a total noob at PHP..I can't seem to be doing anything but pulling my hair out)
=============================================================================
<?php
// Route registration form processing php
// accepts a serialized data from myRoute.js
//header('Content-Type: application/json');
include_once ("dbConnect.php");
//$sql="SELECT * FROM route";
$routeStarts = "SELECT id, idSignal, km, line_name, direction, route.type
FROM route
JOIN signals
ON startSignal = idSignal";
$routeEnds = "SELECT id, idSignal, km, line_name, direction, route.type
FROM route
JOIN signals
ON endSignal = idSignal";
$routeTracks = "SELECT idRoute, signalName, routeTrack.idTrack, length, firstTrack, pointTrack, prevTrack
FROM routeTrack
JOIN track
ON routeTrack.idTrack = track.idTrack";
/*ORDER BY idRoute";*/
$pointTracks = "SELECT idRoute, routeTrack.idTrack, aLocation, bLocation, aLine, bLine, aTrack, bTrack, type
FROM routeTrack
JOIN points
ON routeTrack.idTrack = aTrack";
$sqlMax = "SELECT MAX(km) FROM signals";
$sqlMin = "SELECT MIN(km) FROM signals";
$max = mysqli_query($con, $sqlMax);
$min = mysqli_query($con, $sqlMin);
$start = mysqli_query($con, $routeStarts);
$rowMax = mysqli_fetch_array($max);
$rowMin = mysqli_fetch_array($min);
$range = $rowMax[0] - $rowMin[0];
// For each route picks up the start signal
while($row1 = mysqli_fetch_array($start)){
$resultArray = array();
$routeName = $row1['id'];
$startSig = $row1['idSignal'];
$startX = ((($row1['km'] - $rowMin[0]) / $range)*1000)+100;
$startY = getYcoordinate($row1['line_name']);
$direction = $row1['direction'];
$resultArray['route'] = $routeName;
$resultArray['startSignal'] = $startSig;
$resultArray['startX'] = $startX;
$resultArray['startY'] = $startY;
$resultArray['direction'] = $direction;
//picking up the end signal for the same route
$end = mysqli_query($con, $routeEnds);
while($row2 = mysqli_fetch_array($end)){
if ($row2['id'] == $routeName){
$endSignal = $row2['idSignal'];
$endX = ((($row2['km'] - $rowMin[0]) / $range)*1000)+100;
$endY = getYcoordinate($row2['line_name']);
$resultArray['endSignal'] = $endSignal;
$resultArray['endX'] = $endX;
$resultArray['endY'] = $endY;
}
}
//now filtering out the track for the particular route , non-point
if ($resultArray['startY'] == $resultArray['endY']){
$tracks = mysqli_query($con, $routeTracks);
while($row3 = mysqli_fetch_array($tracks)){
if ($row3['idRoute'] == $routeName && $row3['firstTrack'] == 1 ){
$xFinish = getXfinish($range, $row3['length']);
$resultArray[$row3['idTrack']] = ['length'=>$row3['length'],
'xStart'=>$startX,
'yStart'=>$startY,
'xFinish'=>$startX + $xFinish,
'yFinish'=>$startY ];
} else if ($row3['idRoute'] == $routeName && $row3['firstTrack'] != 1 ){
foreach ($resultArray as $key => $value) {
if ($row3['prevTrack'] == $key){
$prevXstart = $resultArray[$key]['xFinish'];
$prevYstart = $resultArray[$key]['yFinish'];
}
}
$xFinish = getXfinish($range, $row3['length']);
$resultArray[$row3['idTrack']] = ['length'=>$row3['length'],
'xStart'=>$prevXstart,
'yStart'=>$prevYstart,
'xFinish'=>$prevXstart + $xFinish,
'yFinish'=>$prevYstart
];
}
}
//now filtering out the track for plotting point tracks
} else {
$tracks = mysqli_query($con, $routeTracks);
while($row3 = mysqli_fetch_array($tracks)){
if ($row3['idRoute'] == $routeName && $row3['firstTrack'] == 1 && $row3['pointTrack'] != 1){
$xFinish = getXfinish($range, $row3['length']);
$resultArray[$row3['idTrack']] = ['length'=>$row3['length'],
'xStart'=>$startX,
'yStart'=>$startY,
'xFinish'=>$startX + $xFinish,
'yFinish'=>$startY ];
} else if ($row3['idRoute'] == $routeName && $row3['firstTrack'] != 1 && $row3['pointTrack'] != 1){
foreach ($resultArray as $key => $value) {
if ($row3['prevTrack'] == $key){
$prevXstart = $resultArray[$key]['xFinish'];
$prevYstart = $resultArray[$key]['yFinish'];
}
}
$xFinish = getXfinish($range, $row3['length']);
$resultArray[$row3['idTrack']] = ['length'=>$row3['length'],
'xStart'=>$prevXstart,
'yStart'=>$prevYstart,
'xFinish'=>$prevXstart + $xFinish,
'yFinish'=>$prevYstart
];
// first track and point track
} else if ($row3['idRoute'] == $routeName && $row3['firstTrack'] == 1 && $row3['pointTrack'] == 1){
$pointTrack = mysqli_query($con, $pointTracks);
// not first track and point track
} else if ($row3['idRoute'] == $routeName && $row3['firstTrack'] != 1 && $row3['pointTrack'] == 1){
foreach ($resultArray as $key => $value) {
if ($row3['prevTrack'] == $key){
$prevXstart = $resultArray[$key]['xFinish'];
$prevYstart = $resultArray[$key]['yFinish'];
}
}
$turnPoint = getXfinish($range, ($row3['length']/2));
$pointTrack = mysqli_query($con, $pointTracks);
while($row4 = mysqli_fetch_array($pointTrack)){
if ($row4['idTrack'] == $row3['idTrack']){
$yTurnEnd = getYcoordinate($row4['bLine']);
}
}
if ($row1['direction'] == 'down'){
$resultArray[$row3['idTrack']] = ['xStart'=>$prevXstart,
'yStart'=>$prevYstart,
'xTurnStart'=> $prevXstart + $turnPoint,
'yTurnStart'=> $prevYstart,
'xFinish' => $prevXstart + $turnPoint + 50,
'yFinish' => $yTurnEnd
];
} else {
$resultArray[$row3['idTrack']] = ['xStart'=>$prevXstart,
'yStart'=>$prevYstart,
'xTurnStart'=> $prevXstart - $turnPoint,
'yTurnStart'=> $prevYstart,
'xFinish' => $prevXstart - $turnPoint -50,
'yFinish' => $yTurnEnd
];
}
}
}
}
//print_r($resultArray);
//header('Content-Type: application/json');
echo json_encode($resultArray);
unset($resultArray);
}
function getYcoordinate($line_name){
if ($line_name == 'downSuburban'){
$y= (800/20) * 8; // down Suburban
} else if ($line_name == 'upSuburban'){
$y= (800/20) * 10; // up Suburban
} else if ($line_name =='downMain'){
$y= (800/20) * 12; // down Main
} else if ($line_name == 'upMain'){
$y= (800/20) * 14; // up Main
}
return $y;
}
function getXfinish($trackRange, $trackLength){
return ($trackLength/($trackRange*1000))*1000;
}
// $dataArray = array();
// $dataArray[] = array('idRoute'=>$row['id'], 'startSignal'=>$row['startSignal']);
mysqli_close($con);
?>
You need the dataType rather the data.
$.ajax({
url: "visualiser/visualiser_RouteList.php",
dataType: "JSON",
async: false,
success: function(data){
console.log(data);
}
});
Your response is not being recognised as JSON, so it is not being deserialised. Presently it is being received as a string, hence why accessing by index is giving you the character of the string at that position.
You either need to set the headers in the response in PHP to JSON, or force the jQuery to deserialise it for you using dataType: 'json':
$.ajax({
url: "visualiser/visualiser_RouteList.php",
dataType: 'json',
async: false,
success: function(data){
console.log(data);
}
});
Also, when the response is correctly deserialised to an object, you cannot access it using indexes. You need to use the keys, like this:
data.route; // = '1(M)A'
$.ajax({
url: "Url",
dataType: 'JSON',//'datatype the ajax function expects',
type: "post or get",//action type
data:data to be posted,
async: false,
success: function(data){
console.log(data);
}
});,
refer this for more http://api.jquery.com/jquery.ajax/
As explained in this question & answer thread here, instead of data use dataType and instead of uppercase JSON try using lowercase json:
$.ajax({
url: "visualiser/visualiser_RouteList.php",
dataType: "json",
async: false,
success: function(data){
console.log(data);
}
});

Categories

Resources