I had a form that sent an email via ajax, which had been running smoothly for years. Suddenly, nothing is posted, and I do not understand why.
THE JS:
var name = $("input#name").val();
var email = $("input#email").val();
var telephone = $("input#telephone").val();
var message = $("textarea#message").val();
var dataString = 'name='+ name + '&email=' + email + '&phone=' + phone + '&message=' + message;
$.ajax({
type: "POST",
url: "process.php",
data: dataString,
}
});
Process.php:
<?php
if ($_POST) {
$name = $_POST['name'];
echo : $name;
}
else {
echo 'Nothing is posted';
}
?>
Everytime i use the form, the ajax "works", but "Nothing is posted" appears. I can't find an explanation...
For information, I use Jquery 3.1.1, and PHP 7.0
the correct way of implementing jQuery ajax is:
var name = $("input#name").val();
var email = $("input#email").val();
var telephone = $("input#telephone").val();
var message = $("textarea#message").val();
$.ajax({
type: "POST",
url: "process.php",
data:{
name:name,
email:email,
phone:phone,
message:message
},
});
And the php should be:
<?php
if ($_POST) {
$name = $_POST['name'];
echo $name;
}
else {
echo 'Nothing is posted';
}
?>
jQuery changed type to method in version 1.9. Try changing the ajax call to this:
$.ajax({
method: "POST",
url: "process.php",
data: ...
});
Try this:
if ( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
// POST
} else {
// GET
}
Related
The Problem is in the var a I have created
<script>
$( "#EDITsave" ).click(function() {
var a = parseInt(window.id.charAt(window.id.length-1)) //a gets parsed correctly but nothing happens in ajax until i set a number myself
console.log(a)
$.ajax({
type: "POST",
datatype: "text",
url: "edit.php",
data: {
inputID: a,
inputtxt: //issue is in 'a' here!
document.getElementById("editinputtext").value
},
});
});
</script>
PHP: // PHP CODE FOR AJAX
$inputID = $_POST['inputID'];
$inputtxt = $_POST['inputtxt'];
$sql = "UPDATE Contributions SET inputtxt = '$inputtxt' WHERE inputID = $inputID";
if ($connection->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $connection->error;
}
$connection->close();
?>
I have used ajax post without form. When I click submit button it should get the values of other fields. Post request is not being sent and neither output is being shown. It is returning this error Unexpected identifier
Here are the input fields
<input type="text" name="name" id="name" class="center-block Ename" placeholder="Enter you name">
<textarea class="center-block" name="message" id="message" rows="1" placeholder="Enter your message"></textarea>
<input class="center-block sendBtn" type="submit" id="submit" name="submit" value="Submit">
This is the ajax request.
$(document).ready(function(){
var interval = setInterval($('#submit').click(function(){
var values = {
'name': document.getElementById('name').value,
'message': document.getElementById('message').value
};
$.ajax({
type: "POST",
url: "chat.php",
data: values,
success: function(data){
$("#chat").html(data);
}
});
}),1000);
});
It is sending request to this php page
<?php
include 'db.php';
//Here post data is being assigned to variables
$name = $_POST['name'];
$message = $_POST['message'];
$queryInsert = "INSERT INTO chat(`name`, `message`) VALUES('$name', '$message')";
$queryInsertRun = mysqli_query($con, $queryInsert);
if(!$queryInsertRun){
echo mysqli_error($con);
}
//Here is the output which should be shown
$query = "SELECT * FROM `chat` ORDER BY `name` AND `message` DESC ";
$queryRun = mysqli_query($con, $query);
while($row = mysqli_fetch_assoc($queryRun)){
$name = $row['name'];
$message = $row['message'];
?>
<span class="name" style="font-weight: bold"><?php echo $name?>:</span>
<span class="message"><?php echo $message.'<br>'?></span>
<hr>
<?php
}
?>
I want to know that why is this not working.
try this code
function ajaxcall()
{
console.log('i am called');
var values = {
'name': document.getElementById('name').value,
'message': document.getElementById('message').value
};
$.ajax({
type: "POST",
url: "chat.php",
data: values,
success: function(data){
$("#chat").html(data);
}
});
}
$(document).ready(function(){
var id = setInterval(function() {
ajaxcall();
}, 1000);
});
http://jsfiddle.net/cod7ceho/116/
You want to display data if you clicked submit button , use simple click function . Using setInterval can't help you for clicking submit .
JS
$(document).ready(function(){
$('#submit').click(function(){
var values = {
'name': document.getElementById('name').value,
'message': document.getElementById('message').value
};
$.ajax({
type: "POST",
url: "chat.php",
data: values,
success: function(data){
$("#chat").html(data);
}
});
});
});
It sounds like your JSON Data is not valid.
var data = JSON.stringify(values);
var request = $.ajax({
url: "script.php",
method: "POST",
data: data,
dataType: "html" // read about dataType
});
I have jQuery Ajax Autosuggest using jSon.
Now I have problem when showing the data. The data get from mysql data using PHP (looping data) but when get the result, it always show 1 row.
Here is my js code:
$.ajax(
{
type: "GET",
data: post_string,
dataType: "json",
cache: false,
url: 'search.php',
success: function(data)
{
full_name = data[0].full_name;
username = data[0].username;
$("#divResult").show();
$(".display_box").html(username);
}
});
and the search.php
$getSearchWord = mysqli_real_escape_string($con, $_GET['searchword']);
$json = array();
$searchQuery = mysqli_query($con, "SELECT * FROM tb_users WHERE username LIKE '%$getSearchWord%' OR full_name LIKE '%$getSearchWord%' LIMIT 5");
while($searchFetchData = mysqli_fetch_array($searchQuery))
{
$json[] = array(
'username' => $searchFetchData['username'],
'full_name' => $searchFetchData['full_name']
);
}
echo json_encode($json);
and html div to display
<div id="divResult">
<div class="display_box"></div>
</div>
Json
To clear out the field, call this before the Ajax request:
$("#divResul").hide(200);
$(".display_box").html('');
You can try to run all returned array before putting it in your .display_box. Get the length of array returned from search.php then run it in a loop.
success: function(data){
$("#divResult").show(200);
var n = data.length;
for(var x = 0; x < n; x++){
$(".display_box").append(data[x].full_name);
$(".display_box").append(data[x].username);
}
}
No Json
OR without using json. From your search.php:
$table = '<table>';
$getSearchWord = mysqli_real_escape_string($con, $_GET['searchword']);
$json = array();
$searchQuery = mysqli_query($con, "SELECT * FROM tb_users WHERE username LIKE '%$getSearchWord%' OR full_name LIKE '%$getSearchWord%' LIMIT 5");
while($searchFetchData = mysqli_fetch_array($searchQuery))
$table .= '<tr>
<td>'.$searchFetchData['username'].'</td>
<td>'.$searchFetchData['full_name'].'</td>
</tr>';
}
$table .= '</table>';
echo $table; /* RETURN THIS TO YOUR AJAX REQUEST */
Then on your Ajax request:
$.ajax(
{
type: "GET",
data: post_string,
url: 'search.php',
success: function(data)
{
$("#divResult").show(200);
$(".display_box").html(data);
}
});
In ajax send data like this, it may work for you
$.ajax(
{
type: "GET",
data : { searchword: "keyword"},
dataType: "json",
cache: false,
url: 'search.php',
success: function(data)
{
full_name = data[0].full_name;
username = data[0].username;
$("#divResult").show();
$(".display_box").html(username);
}
});
Please try this in your success callback. All you need is to iterate with a $.each() and append to the div.
success: function(data)
{
$.each(data,function(index,value) {
full_name = value[0].full_name;
username = value[0].username;
$(".display_box").append(username . '<br/>');
})
$("#divResult").show();
}
I have read many answers on stack overflow but I can't find an apt answer. I want to send multiple variables from php file to a javascript file. I want to use those variables later separately. So please explain with a simple example of how to get the variables from php file and how to use them separately later.
This is my js.
<script>
function here(card_numb) {
alert("pk!");
$.ajax({
url: 'details.php',
type: "GET",
dataType: 'json',
data: ({
card_number: card_numb
}),
success: function(data) {
console.log('card_number:'+data.card_number+'book_issued:'+data.book_isued);
}
});
}
I'm getting the alert 'pk!'. But $.ajax ain't working.
This is details.php
<?php
if(isset($_GET['card_number'])){
$card_number = $_GET['card_number'];
$query = "Select * from users where card_number = '".$card_number."'";
$query_run = mysqli_query($link,$query);
$row_numb =#mysqli_num_rows($query_run);
if($row_numb == 0){
echo "<div class='bdiv1'>No such number found!</div>";
} else{
$row=mysqli_fetch_assoc($query_run);
$book1 = $row['user_name'];
$arr = array('isued_book' => $book1,'card_number' => $card_number);
echo json_encode($arr);
exit();
}
}
?>
Thank you!
somthing.js - ur jspage
<script>
function here(card_numb) {
$.ajax({
url: 'details.php',
type: 'GET',
dataType: 'json',
data: {
card_number: card_numb
},
success: function(data) {
console.log('card_number:'+data.card_number+'book_issued:'+data.isued_book);
}
});
}
success: function(result){
console.log('variable1:'+result.var1+'variable2:'+result.var2+'variable3:'+result.var3);
} });
details.php
<?php
if(isset($_GET['card_number'])){
$card_number = $_GET['card_number'];
$query = "Select * from users where card_number = ".$card_number;
$query_run = mysqli_query($link,$query);
$row_numb =#mysqli_num_rows($query_run);
if(!$query_run){
echo "<div class='bdiv1'>No such number found!</div>";
} else {
$row=mysqli_fetch_assoc($query_run);
$book1 = $row['user_name'];
$arr = array('isued_book' => $book1,'card_number' => $card_number);
echo json_encode($arr);
exit();
}
if the currect value get in $row you can get the result in console
I am doing an ajax call like this:
function myCall() {
var request = $.ajax({
url: "ajax.php",
type: "GET",
dataType: "html"
});
request.done(function(data) {
$("image").attr('src',data);
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
}
This is my ajax.php:
<?php
$connection = mysql_connect ("",
"", "");
mysql_select_db("");
// QUERY NEW ONE
$myquery = "SELECT * FROM mytable ORDER BY rand() LIMIT 1";
$result = mysql_query($myquery);
while($row = mysql_fetch_object($result))
{
$currentid = "$row->id";
$currentname = "$row->name";
$currenturl = "$row->url";
$currentimage = "$row->image";
echo $currenturl,$currentnam, $currenturl,$currentimage;
}
mysql_close($connection);
?>
My data variable from the ajax call now contains all variables at once:
($currenturl,$currentnam, $currenturl,$currentimage)
How can I separate them so I can do something like:
request.done(function(data) {
$("id").attr('src',data1);
$("name").attr('src',data2);
$("url").attr('src',data3);
$("image").attr('src',data4);
});
jQuery :
$.ajax({
type:"POST",
url:"ajax.php",
dataType:"json",
success:function(response){
var url = response['url'];
var name = response['name'];
var image = response['image'];
// Now do with the three variables
// $("id").attr('src',data1);
// $("name").attr('src',data2);
// $("url").attr('src',data3);
// $("image").attr('src',data4);
},
error:function(response){
alert("error occurred");
}
});
From your code:
echo $currenturl,$currentnam, $currenturl,$currentimage;
Replace the above line with the code below:
$array = array('url'=>$currenturl, 'name'=>$currentname, 'image'=>$currentimage);
echo json_encode($array);
instead of string return an array i.e. use json type for returning value
i.e instead of
echo $currenturl,$currentnam, $currenturl,$currentimage;
use
echo json_encode array('current' => $currenturl,'currentnam' => $currentnam, 'currenturl' => $currenturl,'currentimage' => $currentimage);
and also write 'dataType' as 'json' in ajax