I submitting a form by using an ajax request which posts values to a php script which then stores those values in a database. This is my ajax post:
$.ajax({
type:"POST",
url: "wp-content/plugins/super-plugin/process.php",
'data': 'datastring',
success: function() {
$('#formwrapper').html("<div id='message'></div>");
$('#message').html("<h2>Contact form submitted!</h2>")
.append("<p>We will be in touch soon.</p>").hide().fadeIn(1500, function() {
$('#message').append("<img id='checkmark' src='images/check.png' />");
});
}
});
And this is my PHP file:
$full = explode("&", $_POST["data"]);
$fname = explode(":", $full[0]);
$name = $fname[1];
$femail = explode(":", $full[1]);
$email = $femail[1];
$fphone = explode(":", $full[2]);
$phone = $fphone[1];
$conn = mysqli_connect("localhost", "Andrew", "Change0", "plugindatadb");
mysqli_query($conn, "INSERT INTO data (Name, Email, Phone) VALUES ('$name', '$email', '$phone')");
The data in datastring is formatted by "name:Bo&email:bob#mail&phone:0786754333". However for some reason I can't use those variables sent in my php script? For some reason the php script does not run as well.
You mentioned that you set formatted query params in variable datastring, then in that case, you should use that like shown below in ajax request (remove quotes for data and datastring).
$.ajax({
type:"POST",
url: "wp-content/plugins/super-plugin/process.php",
data: datastring,
success: function() {
$('#formwrapper').html("<div id='message'></div>");
$('#message').html("<h2>Contact form submitted!</h2>")
.append("<p>We will be in touch soon.</p>").hide().fadeIn(1500, function() {
$('#message').append("<img id='checkmark' src='images/check.png' />");
});
}
});
remove '' from datastring ,
data: datastring
bt this is not proper way to pass data pass into json like data ,
$.ajax({
type:"POST",
url: "wp-content/plugins/super-plugin/process.php",
'data': {
name:"Bo",email:"bob#mail",phone:"0786754333"
},
success: function() {
$('#formwrapper').html("<div id='message'></div>");
$('#message').html("<h2>Contact form submitted!</h2>")
.append("<p>We will be in touch soon.</p>").hide().fadeIn(1500, function() {
$('#message').append("<img id='checkmark' src='images/check.png' />");
});
}
});
and into php page.
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
Firstly, in:
'data': 'datastring',
If "datastring" is a variable, as indicated by your description of it's format, those values shouldn't be in quotes. So:
data: datastring,
Secondly, if your PHP script assumes that the data passed in can be split into various components and it accesses those array elements without first verifying that the data is in the required format (or at least that those array elements exist) then it will throw an exception if the data is invalid. This is currently happening because the data is 'datastring'. You should always validate input parameters as it saves time in the long run.
Change the data in ajax call as
data : { datastring : datastring },
In php access it like $_POST['datastring'].
Related
I am trying to get my db rows from php. Currently the js success function isn't being reached. Is there anything obvious in the php that may be causing an issue?
The php
$id=$_GET['id'];
$stmt = $db->prepare("SELECT * FROM brand_members WHERE Id = :id");
$stmt->bindValue(':id',$id,PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($result);
The js
$.ajax({
url: 'dead.php', //the script to call to get data
data: "id=8",
dataType: 'json', //data format
success: function(data) //on recieve of reply
{
var id = data[0]; //get id
var vname = data[1]; //get name
alert("a"); //get name
}
});
The problem is you didn't passed properly your $_GET parameter
To solve that
Change your
url: 'dead.php'
to
url: 'dead.php?id=8',
also data: your_data is no longer needed
Or this method change
data: "id=8"
to
data: {id: 8}
Also in your callback since your ajax response returns an array specified the index 0
success: function(data) //on recieve of reply
{
var id = data[0]['Id']; //get id
var vname = data[0]['name']; //get name
alert("a");
}
I've got this variable $type and I want it to be month or year.
It should be changed by pressing a div.
I've tried creating an onclick event with an ajax call.
The ajax call and the variable are in the same script (index.php)
Inside the onclick function:
var curr_class = $(this).attr('class');
$.ajax({
type: "POST",
url: "index.php",
data: {
type: curr_class
},
dataType: 'text',
success: function(data) {
// Test what is returned from the server
alert(data);
}
});
But the alert returns the whole html page.
When I console.log the data (create a var data = { type:curr_class }) and console.log *that data* it returnstype = month` (which is correct)
while I just want it to return month or year
So on top of the page I can call
if(empty($_POST['type'])){
$type = 'month';
} else {
$type = $_POST['type'];
}
and change the PHP variable so I can use it in the rest of my script.
But how can I accomplish this?
With kind regards,
as you are sending request to the same page so as a result full page is return .You will have to send it to another page and from that page return the type variable
if(empty($_POST['type'])){
$type = 'month';
} else {
$type = $_POST['type'];
echo $type;
keep this code in separate file and make an ajax call to that page
//Try This It's Work
Get Value
Get Value
$(".btn-my").click(function(){
var curr_class = $(this).data('title');
$.ajax({
type: "POST",
url: "index.php",
data: {
type: curr_class
},
dataType: 'text',
success: function(data) {
// Test what is returned from the server
alert(data);
}
});
});
I'm trying post data to PHP file but i can't receive any data from PHP file. Let me add codes.
This is my jQuery function:
$(document).ready(function () {
$(function () {
$('a[class="some-class"]').click(function(){
var somedata = $(this).attr("id");
$.ajax({
url: "foo.php",
type: "POST",
data: "id=" + somedata,
success: function(){
$("#someid").html();
},
error:function(){
alert("AJAX request was a failure");
}
});
});
});
});
This is my PHP file:
<?php
$data = $_POST['id'];
$con = mysqli_connect('localhost','root','','somedatabase');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"database");
$sql="SELECT * FROM sometable WHERE id = '".$data."'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
echo $row['info'];
}
mysqli_close($con);
?>
This what i have in HTML file:
<p id="someid"></p>
Data1
Data2
Note: This website is horizontal scrolling and shouldn't be refreshed. When i'm clicking links (like Data1) it's going to another page without getting data from PHP file
You have a few problems:
You are not using the data as mentioned in the other answers:success: function(data){
$("#someid").html(data);
},
You are not cancelling the default click action so your link will be followed:$('a[class="some-class"]').click(function(e){
e.preventDefault();
...;
As the id's are integers, you can use data: "id=" + somedata, although sending an object is safer in case somedata contains characters that need to be escaped:data: {"id": somedata},;
You have an sql injection problem. You should cast the variable to an integer or use a prepared statement:$data = (int) $_POST['id'];;
As also mentioned in another answer, you have two $(document).ready() functions, one wrapping the other. You only need one.
success: function(){
$("#someid").html();
},
should be:
success: function(data){
$("#someid").html(data);
},
You should add parameter in success
success: function(data){ //Added data parameter
console.log(data);
$("#someid").html(data);
},
The data get the values what you echo in PHP end.
This:
success: function(data){
$("#someid").html(data);
},
and you have two document ready, so get rid of:
$(document).ready(function () { ...
});
data: "id=" + somedata,
Change it to:
data: { id : somedata }
I am having problems passing the variable to the php page.
Here is the code below:
var varFirst = 'something'; //string
var varSecond = 'somethingelse'; //string
$.ajax({
type: "POST",
url: "test.php",
data: "first="+ varFirst +"&second="+ varSecond,
success: function(){
alert('seccesss');
}
});
PHP:
$first = $_GET['first']; //This is not being passed here
$second = $_GET['second']; //This is not being passed here
$con=mysqli_connect("localhost","root","pass","mydb");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"INSERT INTO mytable (id, first, second) VALUES ('', $first, $second)");
mysqli_close($con);
}
I'm I missing something? The actual data is saving to the database BUT $first and $second value is not being passed to the php file.
You are using the POST type, retrieve it in POST :
$first = $_POST['first'];
$second = $_POST['second'];
Or change your JQuery call :
$.ajax({
type: "GET",
url: "test.php",
data: "first="+ varFirst +"&second="+ varSecond,
success: function(){
alert('seccesss');
}
});
This is appening because your are passing data throw POST method and try to get with GET so change those two lines
$first = $_POST['first']; //This is not being passed here
$second = $_POST['second']; //This is not being passed here
Or simply change your method to GET in your jquery
type: "GET"
You are using type: "POST" in ajax and trying to fetch using $_GET, try
$first = $_REQUEST['first']; //This is not being passed here
$second = $_REQUEST['second'];
And there is a method to pass data like that
$.ajax({
type: "POST",
url: "test.php",
data: {first: varFirst,second: varSecond},
success: function(){
alert('seccesss');
}
});
And there you can use
$_POST['first'];
$_POST['second'];
Hope it helps.
I have created a simple tagging system for my schools websites for the students. Now the tagging system is working perfectly now i also have to save tags in a notifications table with respective article id to later notify the students which article they have been tagged in even that i managed to do. But now if by chance you want to remove the tags sometime realizing while typing the article you don't need to tag that person, then the first put tag also gets updated in the db.
//ajax code (attach.php)
<?php
include('config.php');
if(isset($_POST))
{
$u=$_POST['v'];
mysql_query("INSERT INTO `notify` (`not_e`) VALUES ('$u')");
}
?>
// tagsystem js code
<script type="text/javascript">
var id = '<?php echo $id ?>';
$(document).ready(function()
{
var start=/%/ig;
var word=/%(\w+)/ig;
$("#story").live("keyup",function()
{
var content=$(this).text();
var go= content.match(start);
var name= content.match(word);
var dataString = 'searchword='+ name;
if(go.length>0)
{
$("#msgbox").slideDown('show');
$("#display").slideUp('show');
$("#msgbox").html("Type the name of someone or something...");
if(name.length>0)
{
$.ajax({
type: "POST",
url: "boxsearch.php",
data: dataString,
cache: false,
success: function(html)
{
$("#msgbox").hide();
$("#display").html(html).show();
}
});
}
}
return false();
});
$(".addname").live("click",function()
{
var username=$(this).attr('title');
$.ajax({
type: "POST",
url: "attach.php",
data: {'v': username},
});
var old=$("#story").html();
var content=old.replace(word,"");
$("#story").html(content);
var E="<a class='blue' contenteditable='false' href='profile2.php?id="+username+"'>"+username+"</a>";
$("#story").append(E);
$("#display").hide();
$("#msgbox").hide();
$("#story").focus();
});
});
</script>
Looks like your problem appears on the if statement in php code:
even though $_POST['v'] is empty and the sql still get excuted.
There is the quote from another thread:
"
Use !empty instead of isset. isset return true for $_POST because $_POST array is superglobal and always exists (set).
Or better use $_SERVER['REQUEST_METHOD'] == 'POST'
"
Or in my opinion.
Just put
if ($_POST['v']){
//sql query
}
Hope it helps;)
<?php
include('config.php');
$u = $_POST["v"];
//echo $a;
if($u != '')
{
mysql_query("your insert query");
}
else
{
}
?>