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

<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

Related

JS array not being passed to php file?

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

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.

jQuery AJAX post doesn't work on all computers

I have a simple form that sends data using jQuery/Ajax/PHP. The PHP code validates the input before it sends it to the database and returns an error message to the response div if the input is invalid.
It works great on my computer and on my own server. But when I upload it to the client's server it doesn't work as expected. I noticed the following when I access the page from the client's server:
The validation result is being sent to the response div only if ALL the input fields have values. If any of the fields is empty, then nothing happens and no validation message is returned.
It doesn't seem to be a machine issue because I'm using the same computer to access the 3 copies, the one on my localhost, the one on my server, and the one on the client's server.
Here is the code; the jQuery:
$(document).ready(function() {
$('#signup').click(function() {
var queryString = 'ajax=true';
var txtName = encodeURIComponent($('#txtName').val());
if(txtName.length > 0){
txtName = txtName.replace(/\%/g, '-');
}
var txtEmail = escape($('#txtEmail').val());
var txtPhone = encodeURIComponent($('#txtPhone').val());
if(txtPhone.length > 0){
txtPhone = txtPhone.replace(/\%/g, '-');
}
var txtPhoneCode = encodeURIComponent($('#txtPhoneCode').val());
if(txtPhoneCode.length > 0){
txtPhoneCode = txtPhoneCode.replace(/\%/g, '-');
}
queryString = queryString + '&txtEmail=' + txtEmail;
queryString = queryString + '&txtName=' + txtName;
queryString = queryString + '&txtPhone=' + txtPhone;
queryString = queryString + '&txtPhoneCode=' + txtPhoneCode;
$.ajax({
type: "GET",
url: 'send.php',
data: queryString ,
success: function(msg) {
$('#response').html(msg);
}
});
return false;
});
});
The PHP page:
<?php
if(isset($_GET['ajax']) && ($_GET['ajax'] == 'true')){
$name = trim($_GET['txtName']); // coming from input text
$email = trim($_GET['txtEmail']); // coming from input text
$phone = trim($_GET['txtPhone']); // coming from input text
$phonecode = trim($_GET['txtPhoneCode']); // coming from a select
if(strlen($name) == 0){
echo 'Please enter your name';
}
elseif(strlen($email) == 0){
echo 'Please enter your email';
}
elseif(!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*$/i", $email)){
echo 'Please enter a valid email';
}
elseif(strlen($phonecode) == 0){
echo 'Please select phone code';
}
elseif(strlen($phone) == 0){
echo 'Please enter your phone';
}
elseif(!preg_match("/^[0-9]*$/i", $phone)){
echo 'Please enter a valid phone';
}
else{
require('config.php');
// send to mysql db
$email = stripslashes($email);
$name = urldecode(str_replace('-', '%', $name));
$phone = urldecode(str_replace('-', '%', $phone));
$phonecode = urldecode(str_replace('-', '%', $phonecode));
$dt = gmdate("Y-m-d H:i:s");
$sql = "insert into subscribers(datecreated, name, email, phone, phonecode) values('$dt', '$name', '$email', '$phone', '$phonecode')";
$result = mysql_query($sql) or die('Error: Failed to save subscription!');
// redirect
echo '<script>setTimeout(function(){ window.location = "thankyou.html#ty"; }, 0);</script>';
}
}
?>
You are not posting data to the server since you are setting type: "GET".
This means that an HTTP GET request is sent, not HTTP POST. GET requests are typically cached by the client and therefore you may experience that no request is sent at all (when some combinations of field values are used) because the response of that request is already in the client's cache.
You should change your code (both javascript and php) to use HTTP POST instead. The reason for this is twofold:
POST responses are not cached, so a new request will be sent each time you submit.
GET should not be used for requests that may have side effects.

jQuery plugin Validation email check if else CRAZY WIERD

I have successfully implemented the Jquery Validation Plugin http://posabsolute.github.com/jQuery-Validation-Engine/ but i am now trying to get an ajax database email check to work (email exists / email available) and i have written some php script to get this done. Its kinda working but i am getting the most unexpected heretically odd behavior from my IF ELSE statement (seems really crazy to me). observe ### marked comments
PHP code: LOOK AT THE IF ELSE STATEMENT
/* RECEIVE VALUE */
$validateValue = $_REQUEST['fieldValue'];
$validateId = $_REQUEST['fieldId'];
$validateError = "This username is already taken";
$validateSuccess = "This username is available";
/* RETURN VALUE */
$arrayToJs = array();
$arrayToJs[0] = $validateId;
$req = "SELECT Email
FROM business
WHERE Email = '$validateValue'";
$query = mysql_query($req);
while ($row = mysql_fetch_array($query)) {
$results = array($row['Email']);
}
if (in_array($validateValue, $results)) {
$arrayToJs[1] = false;
echo json_encode($arrayToJs); // RETURN ARRAY WITH ERROR ### popup shows "validating, please wait" then "This username is already taken" when email typed is in database - i.e. Working
file_put_contents('output.txt', print_r("1 in array - Email is Taken " . $validateValue, true)); ### this runs!!
}else{
$arrayToJs[1] = true; // RETURN TRUE
echo json_encode($arrayToJs); // RETURN ARRAY WITH success ### popup shows "validating, please wait" when email typed is NOT in the database - i.e. not Working
file_put_contents('output.txt', print_r("2 else - Email is available " . $validateValue, true));
//### THIS RUNS TOO !!!!!!!!!!!!! i.e. echo json_encode($arrayToJs) wont work for both.. If I change (in_array()) to (!in_array()) i get the reverse when email is in database.
//i.e. only the else statements echo json_encode($arrayToJs) runs and the popup msg shows up green "This username is available" crazy right???
//so basically IF ELSE statements run as expected (confirmed by output.txt) but only one echo json_encode($arrayToJs) will work.!!!!
//If i remove the json_encode($arrayToJs) statements and place it once after the IF ELSE statement i get the same problem.
//both $arrayToJs[1] = false; and $arrayToJs[1] = true; can work separately depending on which is first run IF or ELSE but they will not work in the one after another;
}
HERE IS THE REST OF THE CODE-->
1-HTML FORM INPUT CODE:
<tr>
<td> <Label>Business Email</Label>
<br>
<input type="text" name="Email" id="Email" class="validate[required,custom[email],ajax[ajaxUserCallPhp]] text-input">
</td>
</tr>
2-Relevant JQUERY code in jquery.validationEngine.js:
$.ajax({
type: type,
url: url,
cache: false,
dataType: dataType,
data: data,
form: form,
methods: methods,
options: options,
beforeSend: function() {
return options.onBeforeAjaxFormValidation(form, options);
},
error: function(data, transport) {
methods._ajaxError(data, transport);
},
success: function(json) {
if ((dataType == "json") && (json !== true)) {
// getting to this case doesn't necessary means that the form is invalid
// the server may return green or closing prompt actions
// this flag helps figuring it out
var errorInForm=false;
for (var i = 0; i < json.length; i++) {
var value = json[i];
var errorFieldId = value[0];
var errorField = $($("#" + errorFieldId)[0]);
// make sure we found the element
if (errorField.length == 1) {
// promptText or selector
var msg = value[2];
// if the field is valid
if (value[1] == true) {
if (msg == "" || !msg){
// if for some reason, status==true and error="", just close the prompt
methods._closePrompt(errorField);
} else {
// the field is valid, but we are displaying a green prompt
if (options.allrules[msg]) {
var txt = options.allrules[msg].alertTextOk;
if (txt)
msg = txt;
}
if (options.showPrompts) methods._showPrompt(errorField, msg, "pass", false, options, true);
}
} else {
// the field is invalid, show the red error prompt
errorInForm|=true;
if (options.allrules[msg]) {
var txt = options.allrules[msg].alertText;
if (txt)
msg = txt;
}
if(options.showPrompts) methods._showPrompt(errorField, msg, "", false, options, true);
}
}
}
options.onAjaxFormComplete(!errorInForm, form, json, options);
} else
options.onAjaxFormComplete(true, form, json, options);
}
});
3-Relevent code for ajaxUserCallPhp in jquery.validationEngine-en.js:
"ajaxUserCallPhp": {
"url": "validation/php/ajaxValidateFieldUser.php",
// you may want to pass extra data on the ajax call
"extraData": "name=eric",
// if you provide an "alertTextOk", it will show as a green prompt when the field validates
"alertTextOk": "* This username is available",
"alertText": "* This user is already taken",
"alertTextLoad": "*Validating, please wait"
},
Im sure the problem lies with this echo.
echo json_encode($arrayToJs)
Please help i've spent to long on this and its almost working fully.
To clarify - I basically am trying to code it so that if i type an email in the db it shows red "This username is taken" then if i edit the input box to an email not in the database it changes to green "username is available" at the moment only one json_encode will run in any scenario no matter how i change the if else statement –
Thank you very much in advance.
Ok got it finally after a fiddle. I found that json_encode() returns false when any error or warning is posted. using the php error log file in xampp/php/logs/error_logs file i realised that i was getting an error only when the query result was null making $results = null. this caused an output error preventing json_encode() from echoing true, which is why i only got one response.
To fix it i made sure that the $result array was not empty by using the following code after the query to array part.
if(empty($results)){
$results [0]= ("obujasdcb8374db");
}
The whole code is now
$req = "SELECT Email
FROM business
WHERE Email = '$validateValue'";
$query = mysql_query($req);
while ($row = mysql_fetch_array($query)) {
$results[] = $row['Email'];
}
if(empty($results)){
$results [0]= ("obujasdcb8374db");
}
if (in_array($validateValue, $results)) {
$arrayToJs[1] = 0;
echo json_encode($arrayToJs); // RETURN ARRAY WITH ERROR
} else {
$arrayToJs[1] = 1; // RETURN TRUE
echo json_encode($arrayToJs); // RETURN ARRAY WITH success
}
I was able to change ajax url for ajaxusercallphp, ajaxnamecallphp without modifying the languge file... You need to search for this line inside jaquery.validateEngine.js
Find : _ajax:function(field,rules,I,options)
Then scroll down to the ajax request .ie $.ajax
And change url:rule.url to options.ajaxCallPhpUrl
Then all you have to do is include the url as an option like this:
JQuery("#formid").validateEngine('attach', {ajaCallPhpUrl : "yoururl goes here", onValidationComplete:function(form,status){
})
I was able to change ajax url for ajaxusercallphp, ajaxnamecallphp without modifying the languge file... You need to search for this line inside jaquery.validateEngine.js
Find : _ajax:function(field,rules,I,options)
Then scroll down to the ajax request .ie $.ajax
And change url:rule.url to options.ajaxCallPhpUrl
Then all you have to do is include the url as an option like this:
JQuery("#formid").validateEngine('attach', {ajaCallPhpUrl : "yoururl goes here", onValidationComplete:function(form,status){
})

.Post in jquery

im using the below code in jquery, but my page itself reloading, i dont know where i have made a mistake.
var newstr = $.trim($('#umail').val());
newstr holds the email address
$.post("coding/unsub.php",{email:newstr},function(result){
$("#d_result").html(result);
});
i have
<span id="d_result"></span>
to show the result
my php code is
<?php
include ("../includes/dbcon_.php");
$unsub_sql = mysql_query("Delete FROM TblNewsLetter WHERE Email = '$_GET[email]'");
if (!$unsub_sql)
{
$ds_result = "<p style='font-size:200%;color:red;'>Some Error Occurred! Try Later.</p>";
}
else
{
$ds_result = "<p style='font-size:200%;color:green;'>Successfully Unsubscribed</p>";
}
mysql_close($con);
echo $ds_result;
?>
You said in a comment that you do the Ajax call from a form submit handler. You need to prevent the default submit behaviour, either by using the event object's .preventDefault() method or by returning false from the handler:
$("#yourFormSelectorHere").submit(function(e) {
var newstr = $.trim($('#umail').val());
$.post("coding/unsub.php",{email:newstr},function(result){
$("#d_result").html(result);
});
e.preventDefault();
// and/or
return false;
});
In your sql query
$mail = $_GET['email'];
$query = "DELETE FROM TblNewsLetter WHERE Email = $mail";
$_GET should be changed to $_POST
use like this
$unsub_sql = mysql_query("Delete FROM TblNewsLetter WHERE Email = '".$_POST['email']."'");

Categories