JS array not being passed to php file? - php

I have read through many similar questions and had a look at many ajax php tutorials. But I still cannot find for what reason my array is unable to be passed to my PHP.
I post my JS array here:
function passName() {
$.ajax(
{
type: 'POST',
url: 'eDBase.php',
data: 'array=' + arrays,
success: function(){
}
});
}
Where the data is recieved in PHP through:
$arrays = $_POST(['passed'],true);
if ($arrays !== "") {
echo($arrays);
}
$arraypass = "INSERT INTO clientinfo(first_name, last_name, emails)
VALUES($arrays[1],$arrays[2],$arrays[3])";
if($conn->query($arraypass === true)){
echo'Candidate has been added';
}
else{
echo 'Error thrown while adding candidate to database';
}
mysqli_close($conn);
In my PHP preview I get this error thrown:
https://gyazo.com/57f7faa9ee0869f56f031112b33d29b6
Full code is here:
PHP: https://codeshare.io/50NQjL
HTML: https://codeshare.io/ax1POd
Thanks guys I've been stuck on this issue for about a week now just can't seem to see the problem.
(My PHP code is taking this array and the data from it and then placing it into the database)
EDIT: Code causing error while trying to add to database:
$fname = $_POST['first_name'];
$lname = $_POST['last_name'];
$email = $_POST['email'];
$arraypass = "INSERT INTO clientinfo(first_name, last_name, emails)
VALUES($fname,$lname,$email)";
if($conn->query($arraypass === true)){
echo'Candidate has been added';
}
else{
echo 'Error thrown while adding candidate to database';
}
mysqli_close($conn);

Related

Ajax rejecting JSON created by PHP with "SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data"

I have a page that makes an Ajax call, which retrieves, JSON encodes and returns data from a database. The page was working, but in the midst of making some changes, it's now failing. (Should note that I'm working with a test site and test database as I make the changes.)
The errorThrown parameter of the error case shows me "SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data."
Here's the function with the Ajax call. (I've enhanced what's in the alerts for debugging purposes. I'll rip that back out once things are working.)
function acceptConfCode(){
var emailAddr = $('#email').val();
var confCode = $('#confcode').val();
var fnargs = "ConfirmCode|'" + emailAddr + "'," + confCode ;
$.ajax({
url: 'retrievedata.php',
type: "POST",
async: true,
data: {"functionname":"confirmcode","arguments":fnargs},
dataType: "JSON",
success: function (obj) {
if (!obj.error) {
$('#logininfo').hide();
$('#emailrow').hide();
$('#coderow').hide();
$('#reviewactions').show();
updateListOfActions(obj);
}
else {
success = false;
alert("The confirmation code you entered didn't match or has expired. Please try again. Type 1");
}
},
error: function(xhr, textStatus, errorThrown) {
success = false;
alert("The confirmation code you entered didn't match or has expired. Please try again. Type 2. textStatus = " + textStatus + "; errorThrown = " + errorThrown);
}
});
};
The retrievedata PHP page is mostly a CASE statement. The relevant case is this (again with added debugging code):
case 'confirmcode':
if ($argcount <2) {
$returnval = 'too few arguments';
}
else {
$returnval = confirmcode($argsarray[0], $argsarray[1]);
echo "Back from confirmcode\r\n";
var_dump($returnval);
}
break;
At the end of the page, it returns $returnval.
The key action is in the confirmcode function, which runs a MySQL SP to confirm that the user has a valid email and code, and then calls another function to retrieve the actual data. Here's confirmcode. As the commented out pieces show, I've checked results along the way and I am getting what I expect and it's getting JSON encoded; I've ran the encoded JSON back through JSON_decode() in testing to confirm it was decodable.
function confirmcode($spname, $params, $errorstring = 'Unable to send requested data') {
$conn = connect2db();
$query = "SELECT ".$spname."(".$params.") as result";
//echo $query."\r\n";
$result = mysqli_query($conn, $query);
$allresult = "unknown";
if (!$result) {
$errmessage = mysqli_error($conn);
$allresult = $errmessage;
$allresult = json_encode($allresult);
//echo $errmessage;
die( print_r( mysql_error(), true));
}
else {
//echo "In else case\r\n";
//retrieve list of action submissions
$resultobj = mysqli_fetch_object($result);
if ($resultobj->result == 1) {
//echo "In success subcase\r\n";
$allresult = getsubmissions($conn);
//echo "After getsubmissions\r\n";
//print_r($allresult);
}
else {
//echo "In failure subcase\r\n";
$result = array('error'=>true);
$allresult = $result;
}
//echo "Before JSON encode\r\n";
$finalresult = json_encode($allresult);
//echo "After JSON encode\r\n";
//echo json_last_error_msg()."\r\n";
//var_dump($finalresult);
$allresult = $finalresult;
return $allresult;
}
}
Finally, here's getsubmissions, again with some debugging code:
function getsubmissions($conn) {
echo "In getsubmissions\r\n";
$query = "CALL GetSubmissions()";
$submissions = mysqli_query($conn, $query);
if (!$submissions) {
echo "In failure case\r\n";
$errmessage = mysqli_error($conn);
$allresult = $errmessage;
$allresult = json_encode($allresult);
echo $errmessage;
die( print_r( mysql_error(), true));
}
else {
echo "In success case\r\n";
$rows = array();
while ($row = mysqli_fetch_assoc($submissions)) {
$rows[] = $row;
}
$allresult = $rows; //json_encode($rows);
}
//print_r( $allresult);
return $allresult;
}
What's really weird is I have another page in the site that retrieves almost exactly the same data through an Ajax call with no problem. The one that works contains a few additional fields, and doesn't contain two date fields that are in this result.
In addition, the live version of the site retrieves exactly the same data as here, except from the live database rather than the test database, and it works. While this version of the code has some additional things in it, the only differences in the relevant portions are the debugging items. (That is, I've made changes, but not in the part I'm showing here.) That leads me to think this may be an issue with the test data rather than with the code, but then why does the other page work in the test site?
UPDATE: To try to see whether this is a data problem, I cut the test data way down so that it's only returning a couple of records. I grabbed the generated JSON and ran it through JSONLint.COM and it says it's valid.
UPDATE 2: With the reduced data set, here's the string that's returned from retrievedata.php to the Ajax call:
[{"ActionSource":"https:\/\/www.voterheads.com\/","ActionSourceName":"Wall-of-us","Title":"Sign up to get notified about local meetings","Description":"Sign up at www.voterheads.com to get notified about local meetings. When we did, using the free option, this is what happened: a page popped up with a list of municipality meetings in the zip code we entered. We clicked on one of the meetings, and presto! -- instant access to the date, time, location, and agenda of the meeting. Pretty awesome.","StartDate":null,"EndDate":null,"UrgencyDesc":"Anytime","UrgencyColor":"#00FF00","UrgOrder":"5","DurationDesc":"Ongoing","DurOrder":"6","CostDesc":"Free","CostOrder":"1","Issues":"Advocacy","Types":"Learn","States":"ALL","iID":"20"},{"ActionSource":"https:\/\/actionnetwork.org\/forms\/ctrl-alt-right-delete-newsletter-2","ActionSourceName":"Ctrl Alt Right Delete","Title":"Sign up to learn what the \"alt-right\" is up to","Description":"Understand how the right operates online. Sign up for a weekly newsletter.","StartDate":null,"EndDate":null,"UrgencyDesc":"Anytime","UrgencyColor":"#00FF00","UrgOrder":"5","DurationDesc":"An hour or less","DurOrder":"2","CostDesc":"Free","CostOrder":"1","Issues":"Advocacy","Types":"Learn","States":"ALL","iID":"25"}]
As noted above, JSONLint.COM says it's valid JSON.
I've found a solution, though I'm just starting to understand why it works. On retrievedata.php, I uncommented:
echo $returnval;
just before the Return statement and it's working again. So I think the issue is that since retrievedata is a page, but not a function, the return statement didn't actually return anything. I needed code to actually return the JSON-encoded string.

Why is PHP giving an undefined index notice for a POST variable when Ajax returns correct, and the POST variable does indeed exist?

I understand that similar general questions exist, but none of them follow my specific set of circumstances, and none of them really provide a solution.
Inside the same folder on the server, I have two files: "quiz_maker.php"
and "master_data.php."
I send a JSON object to "master_data.php" from "quiz_maker.php" with the following Ajax code:
if(localStorage.getItem("JSON Question Data Object") != null){
//The JSON object was stringified before saving to localStorage.
var dataString = localStorage.getItem("JSON Question Data Object");
$.ajax({
method: "POST",
url: "master_data.php",
data: { jsonDataObject: dataString },
success: function(msg){
console.log(msg + "\n");
}
});
}
Then, in "master_data.php", I receive it as follows:
if(isset($_POST['jsonDataObject'])){
echo "set";
$masterQuestionData = $_POST['jsonDataObject'];
$masterQuestionData = json_decode($masterQuestionData, TRUE);
//Perform MySQL Queries here.
}
else{
echo "not set";
}
When I run the code on "quiz_maker.php", the Ajax success handler fires, and I receive the string "set" in the console as I would expect. However, if I look at the "master_data.php" file, the string "not set" gets echoed out, and the following notice is displayed:
Notice: Undefined index: `jsonDataObject` in
/home/sites/5a/0/03891393e8/public_html/master_data.php on line 35
Furthermore, all the MySQL queries execute perfectly using the allegedly "undefined index" "jsonDataObject".
What would be the reason why Ajax's success handler fires, gives me the string "set" and all of the queries work, but I get an undefined index notice on master_data.php?
Thank you.
As requested, here is the whole master_data.php file:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
session_start();
$booleanSuccessfulOne = false;
$booleanSuccessfulTwo = false;
$servername = "[REDACTED]";
$username = "[REDACTED]";
$password = "[REDACTED]";
// Create connection
$link = mysqli_connect($servername, $username, $password, $username);
// Check connection
if (mysqli_connect_error()) {
$alert = "Oops! We're having trouble publishing your questions and
answers right now. Please try again later.";
die($alert);
}
if(isset($_POST['jsonDataObject'])){
echo "set";
$masterQuestionData = $_POST['jsonDataObject'];
// Unescape the string values in the JSON array
$masterQuestionData = $_POST['jsonDataObject'];
// Decode the JSON array
$masterQuestionData = json_decode($masterQuestionData, TRUE);
$maxQuestions = $masterQuestionData["statistics"][0]["totalQuestions"];
for($i = 1; $i <= $maxQuestions; $i++){
$question = $masterQuestionData["block"][$i-1]["question"];
$answer = $masterQuestionData["block"][$i-1]["answer"];
$query = "INSERT INTO `master` (`id`, `question`, `solution`)
VALUES('".$i."', '".$question."', '".$answer."') ON DUPLICATE KEY
UPDATE `id` = '".$i."', `question` = '".$question."', `solution` =
'".$answer."'";
mysqli_query($link, $query);
}
$query = "DELETE FROM `master` WHERE `id` > '".$maxQuestions."'";
mysqli_query($link, $query);
}
else{
echo "not set";
}
There shouldn't be spaces in the item key for localstorage. The rest of my suggestions are in the chat comments.
localStorage.getItem("JSON Question Data Object");
Can you try the following below and let us know what happens? Change all of your getItem() and setItem() to have no spaces.
localStorage.getItem("JSON");
I believe it should fix up this issue because the rest of your ajax & php looks fine.
That said, you can use bracket notation if you want
localStorage['JSON Question Data Object']

"$.get(url, function (data, status){ alert(data); }" not working on mysqli

<script type="text/javascript">
function signup() {
var url = "process/sign-up-process.php?" + $("#signup-form").serialize();
// alert(url);
$.get(url, function (data, status) {
alert(data);
});
}
</script>
Page: process/sign-up-process.php code goes below
<?php
require_once('connection.php');
$full_name = filter_input(INPUT_GET, 'full_name', FILTER_SANITIZE_STRING);
$email = $_GET['email'];
$email = filter_var($email, FILTER_VALIDATE_EMAIL);
$user_password = filter_input(INPUT_GET, 'user_password', FILTER_SANITIZE_STRING);
$query = "INSERT INTO registered_users_list (full_name, email, user_password) VALUES ('$full_name', '$email', '$user_password')";
$query1 = mysqli_query($conn, $query);
$count = mysqli_affected_rows($conn);
if($count == 1){
echo "Signed up";
}else{
echo "Sorry";
}
?>
The problem is in "process/sign-up-process.php" page, when I comment out the query code and
echo "Some Random Text"
then the
alert(data)
works. But when I tried to run INSERT query it doesn't work. I think the error must be in PHP improved i.e mysqli string.
I can bet $10 that the page you are requesting returns an error instead of text. In chrome, before sending the AJAX request press F12 and go to Network tab. Click on the () Clear sign to clear all entries if needed. Then when the ajax call proceeds check out the response. It's most probably a mysqli error page (Chrome dev console screenshot: http://image.prntscr.com/image/84e59bfb9caf4c9b9dcf8b5f79844176.png )
Probably even better: Request Monitoring in Chrome
A great tutorial if you don't know what I am talking about: https://www.youtube.com/watch?v=AXGB4tIRNgM

Converting PHP/MySQL Request into jQuery AJAX Request

I am kicking myself in the arse here because i can't for the life of me figure it out...this is supposed to be a quick and dirty project, but, I decided i want to try something new, and I have little to no experience with the AJAX methods in jQuery...I spent quite literally 5 days trying to learn and understand how to appropriately implement the AJAX calls, but to know avail...I learned some basic stuff, but not what i need to execute the code below.
Again, I am wondering how to go about converting this standard request to AJAX using jQuery...
here is my form & php
HTML:
<form action="categories.php?action=newCategory" method="post">
<input name="category" type="text" />
<input name="submit" type="submit" value="Add Categories"/>
</form>
PHP:
<?php
if (isset($_POST['submit'])) {
if (!empty($_POST['category'])) {
if ($_GET['action'] == 'newCategory') {
$categories = $_POST['category'];
$query = "SELECT * FROM categories WHERE category ='$categories' ";
$result = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($result)) {
echo '<script>alert("The Following Catergories Already Exist: ' . $categories . '")</script>';
} else {
// Simply cleans any spaces
$clean = str_replace(' ', '', $categories);
// Makes it possible to add multiple categories delimited by a comma
$array = explode(",", $clean);
foreach ($array as &$newCategory) {
mysql_query("INSERT INTO categories (category) VALUES ('$newCategory')");
}
echo "<script>alert('The following Categories have been added successfully: " . $categories . "')</script>";
}
}
} else {
echo "<script>alert('Please Enter at Least One Category.')</script>";
}
}
?>
here's the proper syntax for making the call in the background and not submitting the form, but still sending/retrieving results.
$(function(){
$('form').submit(function(e){
e.preventDefault(); // stop default form submission
$.ajax({
url: 'categories.php',
data: 'action=newCategory',
success: function(data){
//here we have the results returned from the PHP file as 'data'
//you can update your form, append the object, do whatever you want with it
//example:
alert(data);
}
});
});
});
Also:
I would not do this ->
echo "<script>alert('Please Enter at Least One Category.')</script>";
Just do echo 'Please Enter at Least One Category.';
If you need to create an error system, you can do things like,
echo "Error 1001: <!> Please enter at least One Category!';
Then in your Ajax callback for 'success', we can split the returned object in <!>. Example to follow:
success: function(data){
if($(data+':contains("<!>")'){
var errMsg = $(data).split('<!>');
alert(errMsg[0]+' : '+errMsg[1]);
//above would output - Error 1001 : Please enter at least One Category!;
}
}

"Uncaught SyntaxError: Unexpected token <" in jquery.js. Email signup form with AJAX

I'm trying to build a simple email signup, and I came across this tutorial which seemed to be exactly what I wanted to do (http://net.tutsplus.com/tutorials/javascript-ajax/building-a-sleek-ajax-signup-form/). I don't have much programming knowledge, so this was my best bet at getting something up and running. I followed the tutorial, but unfortunately, I'm having some problems with it.
My problem is when I try to submit an email address, I get Uncaught SyntaxError: Unexpected token < in jquery.js, on line 565.
When I expand the error in Dev Tools, it shows:
jQuery.extend.parseJSON jquery.js:565
$.ajax.success common.js:36
jQuery.Callbacks.fire jquery.js:1046
jQuery.Callbacks.self.fireWith jquery.js:1164
done jquery.js:7399
jQuery.ajaxTransport.send.callback jquery.js:8180
As I said, I'm a rookie with this, so I greatly appreciate any help. I've been researching for a while, but haven't found any issue the same as mine. Some were similar, but I couldn't fix the issue with any of the solutions I came across.
This is the form code:
<form id="newsletter-signup" action="?action=signup" method="post">
<fieldset>
<label for="signup-email">Sign up for email offers, news & events:</label>
<input type="text" name="signup-email" id="signup-email" />
<input type="submit" id="signup-button" value="Sign Me Up!" />
<p id="signup-response"></p>
</fieldset>
</form>
This is the signup JS:
/* SIGNUP */
$('#newsletter-signup').submit(function(){
//check the form is not currently submitting
if($(this).data('formstatus') !== 'submitting'){
//setup variables
var form = $(this),
formData = form.serialize(),
formUrl = form.attr('action'),
formMethod = form.attr('method'),
responseMsg = $('#signup-response');
//add status data to form
form.data('formstatus','submitting');
//show response message - waiting
responseMsg.hide()
.addClass('response-waiting')
.text('Please Wait...')
.fadeIn(200);
//send data to server for validation
$.ajax({
url: formUrl,
type: formMethod,
data: formData,
success:function(data){
//setup variables
var responseData = jQuery.parseJSON(data),
klass = '';
//response conditional
switch(responseData.status){
case 'error':
klass = 'response-error';
break;
case 'success':
klass = 'response-success';
break;
}
//show reponse message
responseMsg.fadeOut(200,function(){
$(this).removeClass('response-waiting')
.addClass(klass)
.text(responseData.message)
.fadeIn(200,function(){
//set timeout to hide response message
setTimeout(function(){
responseMsg.fadeOut(200,function(){
$(this).removeClass(klass);
form.data('formstatus','idle');
});
},3000)
});
});
}
});
}
//prevent form from submitting
return false;
});
And this is the PHP:
<?php
//email signup ajax call
if($_GET['action'] == 'signup'){
mysql_connect('host','user','password');
mysql_select_db('table');
//sanitize data
$email = mysql_real_escape_string($_POST['signup-email']);
//validate email address - check if input was empty
if(empty($email)){
$status = "error";
$message = "You did not enter an email address!";
}
else if(!preg_match('/^[^\W][a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\#[a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\.[a-zA-Z]{2,4}$/', $email)){ //validate email address - check if is a valid email address
$status = "error";
$message = "You have entered an invalid email address!";
}
else {
$existingSignup = mysql_query("SELECT * FROM signups WHERE signup_email_address='$email'");
if(mysql_num_rows($existingSignup) < 1){
$date = date('Y-m-d');
$time = date('H:i:s');
$insertSignup = mysql_query("INSERT INTO signups (signup_email_address, signup_date, signup_time) VALUES ('$email','$date','$time')");
if($insertSignup){ //if insert is successful
$status = "success";
$message = "You have been signed up!";
}
else { //if insert fails
$status = "error";
$message = "Ooops, Theres been a technical error!";
}
}
else { //if already signed up
$status = "error";
$message = "This email address has already been registered!";
}
}
//return json response
$data = array(
'status' => $status,
'message' => $message
);
echo json_encode($data);
exit;
}
?>
Thanks!
UPDATE: Shad - I inserted that code right after 'success:function(data){' Is that correct? After doing that, when trying to submit an email address, I get this in the console, pointing to the line with the newly added code:
Failed:
SyntaxError
arguments: Array[1]
get message: function getter() { [native code] }
get stack: function getter() { [native code] }
set message: function setter() { [native code] }
set stack: function setter() { [native code] }
type: "unexpected_token"
__proto__: Error
<br />
<b>Warning</b>: mysql_num_rows(): supplied argument is not a valid MySQL result resource in <b>/homepages/37/d403623864/htdocs/_php/launch_notify.php</b> on line <b>22</b><br />
{"status":"error","message":"Ooops, Theres been a technical error!"}
Screenshot of Dev Tools with that error. Let me know if you need to see any of the lines expanded or anything: http://i.stack.imgur.com/IwnBr.png
UPDATE #2: Using the code provided by satoshi, I think I made a little progress on figuring out the issue, but I still haven't solved it. I think I narrowed it down to a MySQL connection issue. I tried this code:
<?php
mysql_connect("[DB]","[USER]","[PASS]")
or die(mysql_error());
echo "Connected to MySQL<br />";
mysql_select_db("signups")
or die(mysql_error());
echo "Connected to Database";
?>
And the response I get is:
Connected to MySQL
Access denied for user '[USER]'#'%' to database 'signups'
I've tried a bunch of things, but can't figure it out. My host is 1&1, and I created the table through there using PHPMyAdmin. I've tried different tables, all get the same issue. Here's a screenshot showing the table in PHPMyAdmin: http://i.stack.imgur.com/Oe0Fm.png
Thanks again for all the help so far everyone. I appreciate it.
Your PHP file is warning you because $existingSignup is not a valid resource. This is because your SQL query is invalid. For this reason, because PHP is outputting something unexpected, the page doesn't return a valid JSON response.
Please verify that your mysql_query(...) call returns a valid resource before calling mysql_num_rows(...), like this:
$existingSignup = mysql_query("SELECT * FROM signups WHERE signup_email_address='$email'");
if($existingSignup !== FALSE)
{
if(mysql_num_rows($existingSignup) < 1){
// ...
}
else { //if already signed up
$status = "error";
$message = "This email address has already been registered!";
}
}
else {
$status = "error";
$message = mysql_error();
}
Edit: please note that the query is syntactically correct, I guess you face the problem because you didn't set up the DB table correctly.

Categories