I was working with jQuery in the front end and php in the backend. I had some cross origin problem which I have fixed. but now I am filling up forms (sign up) but db is getting updated, not even empty row. Before I was getting some empty row in db ( I am sure about that, my memory is little hazy about that day! sorry!! ) I am unable to find any problem as errors or success message are not getting hit in jQuery file. I tried http://localhost/signup.php and its showing success message upon connecting to db. So I am sure that its connected to the proper db. I also tried to manual input using that php and i was able to import data as well.
I am adding the jQuery and php code below. I am using all this in XAMPP. Thanks in advance. :)
jQuery:
$("#userReg_btn").click(function(e)
{
//user registration in
var array = [];
var flag = false;
var fullName = $("#uFn").val();
var email = $("#uEa").val();
var mobile = $("#uMn").val();
var nID = $("#uNm").val();
var zip = $("#uZc").val();
var prof = $("#uPc").val();
array.push(fullName);
array.push(email);
array.push(mobile);
array.push(nID);
array.push(zip);
array.push(prof);
alert(array);
console.log(array);
$.ajax({
url:"http://localhost/signup.php",
data:
{
fullName: array[0],
email: array[1],
mobile: array[2],
nID: array[3],
zip: array[4],
prof: array[5],
},
type:"POST",
dataType:"json",
success:function(e){
alert("in success");
alert(e);
console.log("success");
},
error:function(e)
{
alert("error is hit");
alert(e);
console.log(e);
}
});
});
and php file:
<?php
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 01 Jan 2016 00:00:00 GMT');
header('Content-type: application/json');
$con=mysql_connect("localhost","root", "");
mysql_select_db("tester",$con);
$name = $_GET['fullName'];
$email= $_GET['email'];
$mobile= $_GET['mobile'];
$nID = $_GET['nID'];
$zip = $_GET['zip'];
$prof= $_GET['prof'];
$query="INSERT INTO user_reg(fullName,email,mobile,nID,zip,prof) VALUES('$name','$email', '$mobile','$nID','$zip','$prof');";
echo $name;
if(mysql_query($query))
{
echo "success";
}else{
echo mysql_error();
}
//}
?>
Thanks in advance again :)
I found a problem in your php script. In your AJAX call you are declaring the HTTP request as post. But in your php script you are using the $_GET method to look for the variable. Use $_POST.
In your PHP script:
$name = $_GET['fullName']
turns into
$name = $_POST['fullName'];
Do this for all your variables.
The reason why you were getting a blank row is because the variables were blank. By changing the method to $_POST your script will be able to find the variables
Your data object contains an extra ,, that shouldn't be there. Also, if you're sending json (note, I'm not sure you want to, but the headers suggest it):
data: JSON.stringify({
fullName: array[0],
email: array[1],
mobile: array[2],
nID: array[3],
zip: array[4],
prof: array[5]
}),
You will also need to set the contentType of the ajax post:
contentType: 'application/json',
Related
I'm currently having some trouble posting a variable on jQuery for MySQLi SELECT on a PHP page.
Code of jQuery:
$("#carta1").click(function()
{
cartaId = document.getElementById("carta1").value;
console.log(cartaId);
ajaxGetResults = $.ajax({
context: this,
type: "POST",
url: "darResposta.php",
data: {'cartaId' : cartaId},
cache: false,
dataType: "json"
})
.done(function(data){
$('#3').html(data);
console.log("Avançou para a terceira parte");
$("#2").hide();
$("#3").show();
})
.fail(function(){
console.log('Erro ao buscar dados');
$("#2").hide();
$("#3").show();
$('#3').html("Deu erro");
});
});
Code of PHP:
if(!$conn)
{
echo "Falhou a ligação à base de dados";
}
else
{
if(isset($_POST['cartaId']))
{
$cartaId = $_POST['cartaId'];
$res = mysqli_query($conn,"
SELECT cartaNome, cartaDescricao
FROM tarot_cartas
WHERE cartaId = ".$cartaId
);
$data = array();
while($row = mysqli_fetch_assoc($res))
{
$data=$row;
}
echo json_encode($data);
}
}
Tried several approaches to this problem such as putting the $cartaId outside the if statement with a direct $_POST, and nothing happened.
Would appreciate if you could shed some light on this problem.
Thanks for taking the time to read and suggest a solution.
use below code
data: { 'cartaId' : cartaId },
instead of
data: {"data":JSON.stringify({'cartaId' : JSON.stringify(this)})},
Solution:
1.Remove this
data: {"data":JSON.stringify({'cartaId' : JSON.stringify(this)})},
2.Replace This one
data: { cartaId: cartaId }
Hope it works....
The jq you have will post a variable to the url.
To debug you should first check in a console (i use firebug) for mozilla) if the request is sent. Using firebug you can see the names of the POST variables you send.
Following this you should check what values get received on the server side by doing
var_dump($_POST);
Finally get the correct variable into your query. You can also debug the query by viewing the log file or, depending on whether you are using a framework, something like CI:
db->last_query();
my view contains the following code
this.keypadDisplay = Ext.create('Ext.field.Text', {
xtype:'textfield',
disabled: true,
value: ''
});
my ajax request code is
handler: function(b, e) {
var thisUser = this.getValue();
alert(thisUser);
//params[this.getSubmitParamName()] = this.getValue();
Ext.Ajax.request({
url:'http://localhost/sencha2011/keypadapp/code.php',
params: thisUser,
method:'GET',
success: function(response, opts){
var text = response.responseText;
console.log(response.responseText);
alert(thisUser);
//alert(this.getValue());
//alert('Value: ' + this.getValue());
Ext.Msg.alert('success', text);
},
failure: function(response, opts){
Ext.Msg.alert('Error','Error while submitting the form');
console.log(response.responseText);
},
scope: this
});
}
here i'm getting the "this.getValue" successfully. i want to insert to this.getValue to the code table.
my code.php contains the following code
<?php
$con = mysql_connect("localhost","root","");
mysql_select_db('form',$con);
$insert = "INSERT INTO codetable(password) VALUES ('".$_GET['thisUser.value']."')";
if(mysql_query($insert))
{
echo('values inserted successfully');
}
else
{
echo('failure' . mysql_error());
}
?>
here im getting the error as "Undefined index:thisUser.Value in .../keypadapp/code.php " on line 5.
can anyone help me to ? thanks in advance...
Assign param value to variable in ajax call:
Ext.Ajax.request({
url:'http://localhost/sencha2011/keypadapp/code.php',
params: 'thisuser='+thisUser,
Then in php, access the value:
$insert = "INSERT INTO codetable(password) VALUES ('".$_GET['thisuser']."')";
Try changing $_GET['thisUser.value'] to $_GET['thisUser_value'] dots in $_GET and $_POST get converted to underscores in PHP. See this for more info https://stackoverflow.com/a/68742/589909
Update
Looking closer at your code you can't get javascript values of an object in php like you are doing. I assume that thisUser is an object. So when passing it as a param its properties will be posted to the server individually. So if it had a property called foo you would get it like so. $_GET['foo']; also you could dump the get request to see what was sent. var_dump($_GET);
I've been trying to figure out what I have done wrong but when I use my JavaScript Console it shows me this error : Cannot read property 'success' of null.
JavaScript
<script>
$(document).ready(function() {
$("#submitBtn").click(function() {
loginToWebsite();
})
});
</script>
<script type="text/javascript">
function loginToWebsite(){
var username = $("username").serialize();
var password = $("password").serialize();
$.ajax({
type: 'POST', url: 'secure/check_login.php', dataType: "json", data: { username: username, password: password, },
datatype:"json",
success: function(result) {
if (result.success != true){
alert("ERROR");
}
else
{
alert("SUCCESS");
}
}
});
}
</script>
PHP
$session_id = rand();
loginCheck($username,$password);
function loginCheck($username,$password)
{
$password = encryptPassword($password);
if (getUser($username,$password) == 1)
{
refreshUID($session_id);
$data = array("success" => true);
echo json_encode($data);
}
else
{
$data = array("success" => false);
echo json_encode($data);
}
}
function refreshUID($session_id)
{
#Update User Session To Database
session_start($session_id);
}
function encryptPassword($password)
{
$password = $encyPass = md5($password);
return $password;
}
function getUser($username,$password)
{
$sql="SELECT * FROM webManager WHERE username='".$username."' and password='".$password."'";
$result= mysql_query($sql) or die(mysql_error());
$count=mysql_num_rows($result) or die(mysql_error());
if ($count = 1)
{
return 1;
}
else
{
return 0;;
}
}
?>
I'm attempting to create a login form which will provide the user with information telling him if his username and password are correct or not.
There are several critical syntax problems in your code causing invalid data to be sent to server. This means your php may not be responding with JSON if the empty fields cause problems in your php functions.
No data returned would mean result.success doesn't exist...which is likely the error you see.
First the selectors: $("username") & $("password") are invalid so your data params will be undefined. Assuming these are element ID's you are missing # prefix. EDIT: turns out these are not the ID's but selectors are invalid regardless
You don't want to use serialize() if you are creating a data object to have jQuery parse into formData. Use one or the other.
to make it simple try using var username = $("#inputUsername").val(). You can fix ID for password field accordingly
dataType is in your options object twice, one with a typo. Remove datatype:"json", which is not camelCase
Learn how to inspect an AJAX request in your browser console. You would have realized that the data params had no values in very short time. At that point a little debugging in console would have lead you to some immediate points to troubleshoot.
Also inspecting request you would likely see no json was returned
EDIT: Also seems you will need to do some validation in your php as input data is obviously causing a failure to return any response data
Try to add this in back-end process:
header("Cache-Control: no-cache, must-revalidate");
header('Content-type: application/json');
header('Content-type: text/json');
hope this help !
i testet on your page. You have other problems. Your postvaribales in your ajax call are missing, because your selectors are wrong!
You are trying to select the input's name attribute via ID selector. The ID of your input['name'] is "inputUsername"
So you have to select it this way
$('#inputUsername').val();
// or
$('input[name="username"]').val();
I tried it again. You PHP script is responsing nothing. Just a 200.
$.ajax({
type: 'POST',
url: 'secure/check_login.php',
dataType: "json",
data: 'username='+$("#inputUsername").val()+'&password='+$("#inputPassword").val(),
success: function(result) {
if (result.success != true){
alert("ERROR");
} else {
alert("HEHEHE");
}
}
});
Try to add following code on the top of your PHP script.
header("Content-type: appliation/json");
echo '{"success":true}';
exit;
You need to convert the string returned by the PHP script, (see this question) for this you need to use the $.parseJSON() (see more in the jQuery API).
I have just started working on php. It's a very good lang as I'm feeling but some point I get stuck as I'm new to this.
My javascript code
var pv = $("#txtStart").val();
var av = $("#txtStartNextLevel").val();
var au = $("#fileStartPlay").val();
alert(pv+" "+av+" "+au);
var myau = au.split('\\');
$.ajax({
type:"POST",
url:php_url,
data:"{startPoint:"+pv+"nextLevelPoint:"+av+"audioFile:"+myau[myau.length-1]+"}",
contentType:"application/json",
dataType:"json",
success:function(){
alert("done");
},
error:function(){
alert(response);
}
});
My PHP code.
<?php
if(file_exists("Text.txt"))
{
$fileName = "Text.txt";
$fh = fopen($fileName,"a")
$Starts = $_POST["startPoint"];
$NextLevel = $_POST["nextLevelPoint"];
$AudioFileName = $_POST["audioFile"];
$code .=$Starts."*".$NextLevel."_1*".$AudioFileName."\"";
fwrite($fh,$code);
fclose($fh);
}
?>
When I run this it executes but doesn't write the values in the variable
$Starts,$NextLevel,$AudioFileName**.
And further if I write the same ajax procedure in
$.post(php_url,{startPoint:pv,nextLevelPoint:av,audioFile:myau[myau.length-1]},function(data){});
this works fine and write the content in the file.
Also As I'm using post method it should not display the values in Address bar what I'm passing to write. But it's showing those values in both the method.
localhost://myphp.php?txtStart=Start&fileStartPlay=aceduos.jpg&txtStartNextLevel=adfd
Please guide me where I'm lacking...
Replace the value bellow (with quotas)
"{startPoint:"+pv+"nextLevelPoint:"+av+"audioFile:"+myau[myau.length-1]+"}"
to
{startPoint:pv, nextLevelPoint: av, audioFile: myau[myau.length-1]}
Do what Burak TAMTURK said, and also get rid of
contentType:"application/json",
$_POST data should be in content-type application/x-www-form-urlencoded, which is the default.
jQuery(document).ready(function(){
// Set the data text
var dataText = "
{
name: 'John',
time: '2pm'
}";
alert(dataText);
// Create the AJAX request
$.ajax({
type: "POST", // Using the POST method
url: "/ajax/analytics/push", // The file to call
data: dataText, // Our data to pass
success: function() { // What to do on success
alert("Data Loaded: " + dataText);
}
});
});
</script>
hello im still learning ajax. how can we push a array of $_POST?
1.im trying to do something like
var dataText['name'] = 'Jhon';
var dataText['time] = '2pm';
then somehow turns it into
$_POST['name'] = 'Jhon';
$_POST['time'] = '2pm';
then send it to the url..
2.is there a way to debug this ? what im doing now is im writing
# somehow doesnt work becouse its not auto refresh when the ajax sends a post
var_dump($_POST);
# ok heres how i debug it right now.
ob_start();
// write content
$content = $_POST;
ob_end_clean();
file_put_contents('CACHE',$content);
in to a file, i hope there is a better solution for this..
Thankyou for looking in.
Adam Ramadhan
I'm not entirely sure what you're doing. You seem to be building JSON manually (and not doing it correctly) and then passing that (in the JSON-serialised string form) to your file. You then seem to expect it to be parsed by PHP automatically.
It would be better to send it as key-value pairs. You can let jQuery do this for you if you pass in an object. This won't look much different to your existing code:
var dataText =
{
name: 'John',
time: '2pm'
};
Note that I have removed the double quotes. This is primarily because it is illegal to have a JS string covering more than one line without escaping the line breaks. It is also because you want the object to pass into your $.ajax call.
These should be available as $_POST['name'] and $_POST['time'] now.
file_put_contents('CACHE',serialize($content));
or
foreach($_POST as $k => $v) $content .= $k .'='.$v;
jQuery(document).ready(function(){
// Set the data text
var dataText =
{
name: 'John',
time: '2pm'
};
alert(dataText);
// Create the AJAX request
$.ajax({
type: "POST", // Using the POST method
url: "/ajax/analytics/push", // The file to call
data: dataText, // Our data to pass
success: function() { // What to do on success
alert("Data Loaded: " + dataText);
}
});
});
# ok heres how i debug it right now.
ob_start();
# somehow doesnt work becouse its not auto refresh when the ajax sends a post
var_dump($_POST);
$content = ob_get_contents();
ob_end_clean();
file_put_contents('CACHE',$content);