PHP session variable not passed while processing with AJAX - php

I am working on a script that echoes an answer based on a selected value. This will be multiple values later on but for now i'm just testing.
The php script is called trough AJAX so the results will show on the same page.
The only problem is that my variable $brand in this case isn't passed so the script will always return my else statement. I have included the variable in the echo to check wether it was passed, which it isn't. What is going wrong here?
this is my index file code:
<?php
session_start();
?>
<html>
<head>
<title>Test</title>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<script type="text/javascript" src="JS/jquery-1.10.2.js" ></script>
<script>
function myCall(){
var request = $.ajax({
url: "process.php",
type: "post",
dataType: "html"
});
request.done(function(msg) {
$("#response").html(msg);
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
}
</script>
</head>
<body>
<div id="formulier">
<form method="" action="" name="form" id="form">
<label for="brand">Brand</label>
<select id="brand" name="brand">
<option value="" >- Select -</option>
<option value="1">Marlboro (1)</option>
<option value="2">Pall Mall (2)</option>
</select>
<input type="button" value="submit" onclick="myCall();">
</form>
</div>
<div id="response">
</div>
This is my php file (process.php):
<?php
session_start();
$brand = $_POST['brand'];
if( $brand == '1'){
echo "Value is 1";
}
else{
echo "Value is: ".$brand;
}
?>

I see several problems in your script:
at no point you reference the actual fields of your form
I'd rather put the handlers inside the ajax call
Try this:
function myCall(){
var request = $.ajax({
url: "process.php",
type: "post",
dataType: "html",
data: $('#form').serialize(), //here you send the form fields
success: function(msg) {
$("#response").html(msg);
},
error: function(jqXHR, textStatus) {
alert("Request failed: " + textStatus);
}
}
}

You should use json_encode (http://us1.php.net/json_encode) for responding in process.php.

Make sure you set the session variable and read it later (in your php else block), e.g.,
$_SESSION["brand"] = "2";

You should try the define the form attributes
<form method="POST" action="" name="form" id="form">

Related

cannot get value from php ajax

Cannot get value from php true AJAX.
My php code is
<?php
$name = $_POST['name'];
$hobby = $_POST['hobby'];
if (!empty($name and $hobby)){
echo 'Data was succesfully captured';
}else {
echo 'Data was not captured'
}
my html code is
<div id="result"></div>
<form method="post">
<input name="name" type="text" id="name">
<br>
<input name="hobby" type="text" id="hobby">
<input name="snd_btn" type="button" id="snd_btn" value="Save">
</form>
JS
$(document).ready(function(){
$('#snd_btn').click(function() {
var name = $('#name').val();
var hobby = $('#hobby').val();
$.ajax({
url: "save.php",
type: "POST",
dataType: 'json',
data: { name, hobby,
success: function(result) {
$('#result').html(result);
},
}
});
});
});
if i Change in js to
success: function() {
$('#result').html('Data was succesfully captured');
},
it work but not from php
This one is wrong.
if (!empty($name and $hobby)) {
Please replace that with:
if (!empty($name) and !empty($hobby)) {
You have to check for emptiness of the variable for each one.
Problems:
After hobby comes a "}" before ",".
Then, you have an error-prone additional "}". The one after the closing "}," (btw, delete the ",") of success callback.
You forgot the semicolon at the end of the line echo 'Data was not captured'.
The ajax call expects a JSON encoded response, as you defined dataType: JSON. So, in PHP, you must encode the response string - with json_encode.
Since you don't have an error callback (error: function(...){...}) you can't see any errors. So, define one. An example is below.
Recommendations:
Define the data object as below.
The PHP check on empty values should happen as below.
You must also check if the posted values are set.
Don't show any specific error details to the users. Just display a general user-friendly message to them. So, don't do as I did - by printing the error details in the console :-)
index.php:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes" />
<meta charset="UTF-8" />
<!-- The above 3 meta tags must come first in the head -->
<title></title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#snd_btn').click(function () {
var name = $('#name').val();
var hobby = $('#hobby').val();
$.ajax({
method: 'POST',
dataType: 'json',
url: 'save.php',
data: {
'name': name,
'hobby': hobby
},
success: function (result, textStatus, jqXHR) {
$('#result').html(result);
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error! See the console');
console.log(textStatus);
console.log(errorThrown);
console.log(jqXHR);
},
complete: function (jqXHR, textStatus) {
//...
}
});
});
});
</script>
</head>
<body>
<div id="result"></div>
<form method="post">
<input name="name" type="text" id="name">
<br>
<input name="hobby" type="text" id="hobby">
<input name="snd_btn" type="button" id="snd_btn" value="Save">
</form>
</body>
</html>
save.php:
<?php
/*
* Check if the values are set.
* I used here the short "null coalescing operator".
* Search for it in the link below.
*
* #link https://secure.php.net/manual/en/language.operators.comparison.php Comparison Operators.
*/
$name = $_POST['name'] ?? '';
$hobby = $_POST['hobby'] ?? '';
if (!empty($name) && !empty($hobby)) {
$response = 'Data was succesfully captured';
} else {
$response = 'Data was not captured';
}
echo json_encode($response);
First of all you have check that the ajax call will be successfully done or not
If ajax call was successfully done then,
Check the response of success data by print the in console.
Your php code should be like this
<?php
$name = $_POST['name'];
$hobby = $_POST['hobby'];
if ($name and $hobby ){
echo json_encode('Data was succesfully captured');
}else {
echo json_encode('Data was not captured');
}
From php you have to return data in form of json.
And js side:
$(document).ready(function(){
$('#snd_btn').click(function() {
var name = $('#name').val();
var hobby = $('#hobby').val();
$.ajax({
url: "save.php",
type: "POST",
dataType: 'json',
data: { name:name, hobby:hobby} // data in { key : value}
success: function(result) {
res = JSON.parse(res);
console.log(res);// display in developertools > console
$('#result').html(res);
},
}); }); });

PHP Jquery Ajax POST call, not work

As the title says, i have try many times to get it working, but without success... the alert window show always the entire source of html part.
Where am i wrong? Please, help me.
Thanks.
PHP:
<?php
if (isset($_POST['send'])) {
$file = $_POST['fblink'];
$contents = file_get_contents($file);
echo $_POST['fblink'];
exit;
}
?>
HTML:
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.8.3.min.js"></script>
<script>
$(document).ready(function() {
$("input#invia").click(function(e) {
if( !confirm('Are you sure?')) {
return false;
}
var fbvideo = $("#videolink").val();
$.ajax({
type: 'POST',
data: fbvideo ,
cache: false,
//dataType: "html",
success: function(test){
alert(test);
}
});
e.preventDefault();
});
});
</script>
</head>
<div style="position:relative; margin-top:2000px;">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input id="videolink" type="text" name="fblink" style="width:500px;">
<br>
<input id="invia" type="submit" name="send" value="Get Link!">
</form>
</div>
</html>
Your Problem is that you think, that your form fields are automatic send with ajax. But you must define each one into it.
Try this code:
<script>
$(document).ready(function() {
$("input#invia").click(function(e) {
if( !confirm('Are you sure?')) {
return false;
}
var fbvideo = $("#videolink").val();
$.ajax({
type: 'POST',
data: {
send: 1,
fblink: fbvideo
},
cache: false,
//dataType: "html",
success: function(test){
alert(test);
}
});
e.preventDefault();
});
});
</script>
Instead of define each input for itself, jQuery has the method .serialize(), with this method you can easily read all input of your form.
Look at the docs.
And maybe You use .submit() instead of click the submit button. Because the user have multiple ways the submit the form.
$("input#invia").closest('form').submit(function(e) {
You must specify the url to where you're going to send the data.
It can be manual or you can get the action attribute of your form tag.
If you need some additional as the send value, that's not as input in the form you can add it to the serialized form values with formSerializedValues += "&item" + value;' where formSerializedValues is already defined previously as formSerializedValues = <form>.serialize() (<form> is your current form).
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.8.3.min.js"></script>
<script>
$(document).ready(function() {
$("#invia").click(function(e) {
e.preventDefault();
if (!confirm('Are you sure?')) {
return false;
}
// Now you're getting the data in the form to send as object
let fbvideo = $("#videolink").parent().serialize();
// Better if you give it an id or a class to identify it
let formAction = $("#videolink").parent().attr('action');
// If you need any additional value that's not as input in the form
// fbvideo += '&item' + value;
$.ajax({
type: 'POST',
data: fbvideo ,
cache: false,
// dataType: "html",
// url optional in this case
// url: formAction,
success: function(test){
alert(test);
}
});
});
});
</script>
</head>
<body>
<div style="position:relative; margin-top:2000px;">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input id="videolink" type="text" name="fblink" style="width:500px;">
<br>
<input id="invia" type="submit" name="send" value="Get Link!">
</form>
</div>
</body>

how to insert value in database using php, jquery and ajax

I am struggling very hard to get this to work and I don't know what I'm doing wrong. I have a register page that I want to take the data inserted into the form and INSERT it to the database with jQuery and AJAX. I'm not very experienced with AJAX AND jQuery so be gentle! :P I will show you the files that I have...this is a msg.php page when i have submit data sometimes post submit in database`
mostly not so i want to know that why it s happening i am new in this field
<?
php $id=$_GET['id'];
$id1=$_SESSION['id'];
?>
<form method="post" class="msgfrm" id="msgfrm">
<input type="hidden" value="<?php echo $_GET['id']; ?>" name="rcvrid" id="rcvrid">
<input type="hidden" name="senderid" id="senderid" value="<?php echo $id1;?>" >
<div class="msgdiv" id="chatbox"></div>
<div class="textdiv">
<input type="text" name="msg" id="msg" class="textmsg">
<input type="submit" value="Send" onClick="sendChat()">
</div>
</form>
function sendChat()
{
$.ajax({
type: "POST",
url: "msg_save.php",
data: {
senderid:$('#senderid').val(),
rcvrid:$('#rcvrid').val(),
msg: $('#msg').val(),
},
dataType: "json",
success: function(data){
},
});
}
msg_save.php file
<?php
require_once('include/util.php');
$rcvrid=$_POST['rcvrid'];
$senderid=$_POST['senderid'];
$msg=$_POST['msg'];
$sql="insert into message(rcvrid,senderid,msg) values($rcvrid,$senderid,'$msg')";
mysql_query($sql);
?>
$.ajax({
type: "POST",
url: "msg_save.php",
data: " senderid="+$('#senderid').val()+"rcvrid="+$('#rcvrid').val()+"msg="+$('#msg').val(),
dataType: "json",
success: function(data){
},
});
please try this code and send data ,and use post method in php to get data,it will work
if you are trying chat application check this, it is old but just for idea:
http://www.codeproject.com/Articles/649771/Chat-Application-in-PHP
use mysqli_query instead of mysql_query recommended
<?php
$id=$_GET['id'];
//$id1=$_SESSION['id']; COMMENTED THIS AS I AM NOT IN SESSION. HARDCODED IT IN THE FORM AS VALUE 5
?>
<html>
<head>
<script src="//code.jquery.com/jquery-1.10.2.min.js"></script>
</head>
<body>
<form method="post" class="msgfrm" id="msgfrm">
<input type="hidden" value="<?php echo $_GET['id']; ?>" name="rcvrid" id="rcvrid">
<input type="hidden" name="senderid" id="senderid" value="5" >
<div class="msgdiv" id="chatbox"></div>
<div class="textdiv">
<input type="text" name="msg" id="msg" class="textmsg">
<input type="submit" value="Send" >
</div>
</form>
<script>
$("#msgfrm").on("submit", function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "msg_save.php",
data: $(this).serialize(),
success: function(data) {
$("#chatbox").append(data+"<br/>");//instead this line here you can call some function to read database values and display
},
});
});
</script>
</body>
</html>
msg_save.php
<?php
//require_once('include/util.php');
$rcvrid = $_POST['rcvrid'];
$senderid = $_POST['senderid'];
$msg = $_POST['msg'];
echo $rcvrid.$senderid.$msg;
$con = mysqli_connect("localhost", "root", "", "dummy");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "insert into message(rcvrid,senderid,msg) values($rcvrid,$senderid,'$msg')";
mysqli_query($con,$sql);
mysqli_close($con);
echo "successful"
?>
check that whether you have inserted jquery file or not.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
Then include your function sendChat() inside <script> tags.
On submit button
<button type="submit" id="button">SAVE</button>
<script>
$(document).ready(function(){
$("#button").click(function(){
var firstname=$("#firstname").val();
var lastname=$("#lastname").val();
var email=$("#email").val();
$.ajax({
url:'dbConfigAndInsertionQuery.php',
method:'POST',
data:{
firstname:firstname,
lastname:lastname,
email:email
},
success:function(data){
alert(data);
}
});
});
});
</script>

POST data to redirect page fail

I was totally confused by the following situation...
situation
post data from a.php to b.php and redirect to b.php...but fail
CODE
- a.php
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(document).ready(function() {
$('#submit').click(function() {
$.ajax({
url: 'b.php',
dataType: 'html',
type: 'POST',
data: {
value: $('#value').val()
},
error: function(xhr) {
console.log('ajax went wrong!');
},
success: function(response) {
console.log(response);
window.location.href = "b.php";
}
});
});
});
</script>
</head>
<body>
value: <input type="text" id="value">
</body>
</html>
CODE
- b.php
<?php
echo $_REQUEST['value'];
?>
a.php can get the right response from b.php without redirect function. However, once I include the statement window.location.href = "b.php";, a.php will redirect to b.php but without printing anything.
Why is this situation happening?
Is there any solution to fix this?
Thanks!
you can't pass data between to pages in this way. Posting data to b.php and redirecting to it - are two different requests.
if you want to pass data via redirecting - use GET params:
window.location.href = "b.php?value="+$('#value').val();
Also form submission directly to b.php can help you.
<form action="b.php" method="post">
<input name="value" />
<input type="submit" />
</form>
You just need a <form> so that whenever you click on submit button your all form data will be transferred to b.php (YOU WILL AUTOMATICALLY BE REDIRECTED TO b.php page) and you can there access $_POST['value']. That's very simple. No need to do $.ajax call.
<form id="myFrm" name="myFrm" method="post" action="b.php">
value: <input type="text" id="value" name="value">
<input type="submit" id="submit" name="submit" value="submit">
</form>
Your ajax code is working. It is calling the url b.php and printing the value to output. However, the result is not what you expect.
When you made the ajax call and send the data in the form, the evaluation of b.php will be in response when ajax request is successful. Try to make the following change :
From
window.location.href = "b.php";
to
alert(response);
You will see what you send in the input in a message box. Follow your code adapted. Note I added a button to make the call:
index.php
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(document).ready(function() {
$('#submit').click(function() {
$.ajax({
url: 'ajax.php',
dataType: 'html',
type: 'POST',
data: {
value: $('#value').val()
},
error: function(xhr) {
console.log('ajax went wrong!');
},
success: function(response) {
alert(response);
console.log(response);
//window.location.href = "b.php";
}
});
});
});
</script>
</head>
<body>
value: <input type="text" id="value">
<input type=button id="submit" value=go>
</body>
</html>
ajax.php
<?php
echo $_REQUEST['value'];
?>
This is the ajax approach. But if you need only pass the value in the form to b.php, you do not need ajax. Just create a form and use b.php as it action like this:
index.php
<html>
<head>
</head>
<body>
<form method="POST" action="b.php">
value: <input type="text" id="value" name="value">
<input type=submit value=go>
</form>
</body>
</html>
b.php
<?php
echo $_REQUEST['value'];
?>
Note the changes I made in your html.
Try this one, i think this will help you.
Here i create two pages.
one is a.php and another page is b.php
a.php
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(document).ready(function() {
var abc='';
$('#submit').click(function() {
var abc=$('#abc').val();
$.ajax({
url: 'b.php',
dataType: 'html',
type: 'POST',
data: {
value: abc
},
error: function(xhr) {
console.log('ajax went wrong!');
},
success: function(response) {
console.log(response);
var stateObj = { foo: "b" };
history.pushState(stateObj, "page 2", "b.php?value="+response);
$('#hid').hide();
$('#res').html(response);
}
});
});
});
</script>
<html>
<body>
<div id="hid">
Value: <input type="text" id="abc" /> <input type="button" id="submit" value="Get Value" /><br>
</div>
<div id="res"></div>
</body>
</html>
b.php
<?php
echo $_REQUEST['value'];
?>
use
$_post['value'] instead of $_request['value']

Insert record using jQuery after ajax call doesn't work

I have an insert and load record (jQuery & PHP) script working fine without using AJAX. but after the AJAX call, insert (jQuery) doesn't work.
This is my code:-
$(".insert").live("click",function() {
var boxval = $("#content").val();
var dataString = 'content='+ boxval;
if(boxval==''){
alert("Please Enter Some Text");
}
else{
$.ajax({
type: "POST",
url: "demo.php",
data: dataString,
cache: false,
success: function(html){
$("table#update tbody").prepend(html);
$("table#update tbody tr").slideDown("slow");
document.getElementById('content').value='';
}
});
}
return false;
});
$(".load").live("click",function() {
$.ajax({
type: "POST",
url: "test.php",
success: function(msg){
$("#container").ajaxComplete(function(event, request, settings){
$("#container").html(msg);
});
}
});
});
});
Definitely recommend using your browsers dev tools to examine the exact request that is submitted and see if there is a problem there first.
You might also want to change the way you pass the dataString to the ajax request.
If your boxval has a "&" in it then you'll end up with an incorrectly formatted string. So, try initialising data instead as:
var data = {};
data.content = boxval;
This will ask jQuery to escape the values for you.
I'd be curious to see your form markup and your back-end PHP code; it may provide a clue.
Often I'll have a form variable called 'action', just to tell the PHP code what I want it to do (especially if that PHP script is a controller for many different actions on an object). Something like <input type="hidden" name="action" value="insert"/> or even multiple <input type="submit" name="action"/> buttons, each with a different value. In the PHP code I'll have something like:
switch ($_POST['action']) {
case 'insert':
// insert record and send HTML
break;
// other actions
}
If you've done something like this, perhaps the PHP is looking for the presence of a variable that doesn't exist.
Without being able to look at your code, I'd highly recommend the incredibly handy jQuery Form Plugin http://jquery.malsup.com/form/ . It allows you to turn a form into an AJAX form, formats your data properly, and doesn't forget the data from any of your form elements (except <input type="submit"/> buttons that weren't clicked on, which is the same behaviour that a non-AJAX form exhibits). It works just like the standard $.ajax() method.
I solved the problem
I replaced this code
$("#container").ajaxComplete(function(event, request, settings){
$("#container").html(msg);
});
with
$("#container").html(msg);
Thank you very much for your answers
<!--
To change this template, choose Tools | Templates
and open the template in the editor.
-->
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.clicker').click(function(){
var fname = $('.fname').val();
var lname = $('.lname').val();
var message=$('.message').val();
$.ajax({
type:"POST",
url: "submit.php",
cache:false,
data: "fname="+fname+"&lname="+lname+"&message="+message,
success: function(data){
$(".result").empty();
$(".result").html(data);
}
});
return(false);
});
});
</script>
</head>
<body>
<div>Data Form</div>
<form id="form1" name="form1" method="post" action="">
<input name="fname" type="text" class="fname" size="20"/><br />
<input name="lname" type="text" class="lname" size="20"/><br />
<div class="result"><textarea name="message" rows="10" cols="50" class="message"> </textarea></div>
<input type="button" value="calculate" class="clicker" />
</form>
</body>
</html>
submit.php
<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("ajaxdb",$con);
$fname=$_REQUEST['fname'];
$lname=$_REQUEST['lname'];
$message=$_REQUEST['message'];
$sql="insert into person(fname,lname,message) values('$fname','$lname','$message')";
mysql_query($sql) or die(mysql_error());
echo "The data has been submitted successfully.";
?>

Categories