Ajax cannot load data from php to div - javascript

This is the ajax function
$(document).ready(function() {
$('#submit').click(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'searchphp.php',
data: {suburb_id: $('#suburb_id').val()},
success: function(data)
{
$("#tableContent").html(data);
}
});
});
});
this is the php file need to receive data, it worked perfect.
<?php
//Check the form if submit by post
if (isset($_POST["searchBtn"])) {
$strInputSuburb = "";
$strInputSuburb = $_POST["suburb_id"];
//Check if the input box is empty or not
//if BOTH "Suburb" AND "Street" is empty, it will display the error message.
if(!empty($strInputSuburb))
{
//Connect to database server and table
include("connection.php");
#mysqli_select_db($conn, "db")
or die ("Database not available");
$querySql1 = "select * from Infringement
where suburb like '%".mysqli_real_escape_string($conn, $strInputSuburb)."%' and Street1 like '%".mysqli_real_escape_string($conn, $strInputStreet)."%'
order by Suburb, Fines DESC";
$result1 = mysqli_query($conn, $querySql1)
or die ("No information return...");
$count = mysqli_num_rows($result1);
$i=1;
if(!$count==0){
//do stuff, like echo
}
else {
//do stuff
}
//Release the SQL clause
mysqli_free_result($result1);
//Close the connection to database
mysqli_close($conn);
}
else {
//do stuff
}
}
?>
i want load to this div
<div id="tableContent"></div>
the css style is
#tableContent {
width:100%;
height:400px;
}
The input box is below
<input type="textbox" class="form-control" name="suburb" placeholder="Suburb" id="suburb_id" >
<input type="submit"class="btn" name="searchBtn" id='submit' value="Search" />
I used php to get data from form before. after using Ajax, I deleted "form" tag.
Thank you so much.

You're not sending the searchBtn parameter, which the PHP script is checking for. Add it to the data: option.
$(document).ready(function() {
$('#submit').click(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'searchphp.php',
data: {
suburb_id: $('#suburb_id').val(),
searchBtn: 'Search'
},
success: function(data)
{
$("#tableContent").html(data);
}
});
});
});
Or remove that check from the PHP script, and test if (isset($_POST['suburb_id'])) instead.

Related

AJAX giving success but no changes made in database

I am making a function to change the user's email, this call will be made via AJAX on a button click. The form code is below, which is in a file named profile.php:
<form id="changeEmail" method="post">
<div class="form-group">
<label for="changeEmail">Update Email Address</label>
<input type="email" id="email" class="form-control" name="email" value="<?php echo $currentEmail; ?>">
</div>
<button type="submit" id="updateEmail" class="btn btn-success">Update</button>
</form>
I have also created a script in this file as well to perform some basic functionality such as call the ajax function and hide the button until changed. See it below:
<script>
$("#updateEmail").hide();
var id = "<?php echo $id ?>";
$("#email").change(function(){
$("#updateEmail").slideDown();
});
var email = $("#email").val();
console.log("id: " + id);
updateEmail("<?php echo $id; ?>", email);
</script>
The AJAX function which I created is saved in a file named profileAjax.js, this file will hold all my profile ajax functions passing through the users id and new email address.
function updateEmail(id, email) {
$("#updateEmail").click(function(e) {
e.preventDefault(); // Prevent HREF
$("#spinner").show(); // Show spinner
setTimeout(function() {
$.ajax({ // Perform Ajax function
url: "../ajax/admin/updateEmail.php",
dataType: "HTML",
type: "POST",
data: {id: id, email: email},
success: function (result) {
$("#spinner").hide();
$(".dashContent").html(result);
console.log("This worked");
}
});
}, 1500); // Delay this for 1.5secs
});
}
The final file which is called by the AJAX function is updateEmail.php which can be seen below:
include '../../functions/linkAll.inc.php';
$id = filter_input(INPUT_POST, "id");
$email = filter_input(INPUT_POST, "email");
updateEmail($id, $email);
The function which is called updateEmail is saved in an external file and works fully on its own.
function updateEmail($id, $email) {
$connect = db();
$stmt = $connect->prepare("UPDATE `Account` SET `email` = ? WHERE `id` = ?");
$stmt->bind_param("si", $email, $id);
if ($stmt->execute()) {
successMessage("Successfully updated your email address.");
} else {
errorMessage($stmt->error());
}
$stmt->close();
}
However, when the update button is shown and clicked upon, it runs and gives a success message with nothing being updated in the database table itself.
The jQuery AJAX success function is called when the requested source returns HTTP status 200. You should return something from PHP to the AJAX call to tell it if the database action was successfull.
Example PHP (called by AJAX request):
if($stmt->execute()) {
echo "1";
}
else {
echo "0";
}
Example JavaScript:
success: function(data) {
if(data == "1") {
//code if database action is successfull
}
else {
//code if database action failed
}
}

Ajax not returning results

Alright so I have this code which basically finds the user inside the table users and displays it in alert, but it seems that I am doing something wrong. The log shows "Function is not set" and the alert itself displays that.
This is the HTML form I have for it
<center><form method='POST' >
<input id="search_fix" type="text" name="search" placeholder="Search..">
<input type="submit" name="submit_menu_search" style="display: none;">
</form></center>
This is the ajax processing
$(document).ready(function() {
$("#search_fix").keyup(function() {
var search_text = $(this).val();
if(search_text != '') {
$.ajax({
url:"handler.php",
method:"POST",
data:{"function":"search_ajax", search:search_text},
dataType:"text",
success:function(data){
$('#search_result').html(data);
console.log(data);
alert(data);
}
});
}
else {
}
});
});
And these are my PHP functions that I used to basically search for the term
public function search_ajax($term) {
$handler = new sql();
$sql = $handler->connect();
$sql->real_escape_string($term);
$result = $sql->query("SELECT ime FROM users WHERE ime LIKE '%".$term."%'") or die (mysql_error());
if($result->num_rows >= 1){
while($row = $result->fetch_assoc()) {
echo $row['ime'];
}
}
}
if(isset($_POST['function'])) {
switch($_POST['function']) {
case "search_ajax": {
require_once "assembly/user.php";
$user = new User();
$user->search_ajax($_POST['search']);
break;
}
default: {
echo "Unknown AJAX function handler";
break;
}
}
}
else {
echo "Function is not set";
}
It sounds like you're using a version of jQuery before 1.9.0. The method: option didn't exist in the older versions, it was called type:. That's why you're seeing the parameters appended to the URL, because type: "GET" is the default.
So change
method: "POST",
to:
type: "POST",
try this:
$.ajax({
url:"handler.php",
method:"POST",
data:'{"function":"search_ajax", search:search_text}',
dataType:"text"
})
.done(function(data){
$('#search_result').val(data);
console.log(data);
alert(data);
} ) ;

Select value into the textbox FROM ajax using php

I am trying to get the results from the database whether username is available or not . But it is not giving any results i am not getting ajax response this is the html code
<form id="user_form">
<input placeholder="username here" type="text" name="ajax-data" id="ajax-data">
<input type="submit" name="btnSubmit" id="btnSubmit" Value="Submit">
</form>
<span class="php_responce_here"></span>
This is the ajax code which i have used
$(document).ready(function()
{
$("form#user_form").click(function()
{
var textboxvalue = $('input[name=ajax-data]').val();
$.ajax(
{
type: "POST",
url: 'second.php',
data: {ajax-data: textboxvalue},
success: function(result)
{
$(".php_responce_here").html(result);
}
});
});
});​
</script>
final code of php where i have used the validation and the query to find whether the username is available in the database or not the problem is that it is not giving any of the result
<?php
error_reporting(0);
require "config.php";// configuration file holds the database info
$user_name = $_POST['ajax-data']; // textbox in the html
if($user_name)
{
$usernamecheck= mysql_query("SELECT count(*) FROM users WHERE username='$user_name'");
$check= mysql_fetch_row($usernamecheck);
if($check[0]==0)
{
if($user_name!=""){
if(strlen($user_name)>25){
echo "You have reached the maximum limit";
}
else{
echo "User name is valid";
}
}
else
{
echo "username is empty";
}
}
else{
echo "Username Already Taken";
}
}
?>
should be submit event not click:
$("form#user_form").submit(function(e) {
e.preventDefault();
var textboxvalue = $('input[name=ajax-data]').val();
$.ajax(
{
type: "POST",
url: 'second.php',
data: { "ajax-data": textboxvalue },
success: function(result) {
$(".php_responce_here").html(result);
}
});
});
and as #Cyril BOGNOU pointed out;
data: { "ajax-data": textboxvalue }
You should too add data type to be returned with the parameter if you want to return JSON for example
dataType: 'JSON',
and Yes I think you should better write
data: { "ajax-data": textboxvalue }
So the update should be
$(document).ready(function()
{
$("form#user_form").click(function()
{
var textboxvalue = $('input[name=ajax-data]').val();
$.ajax(
{
type: "POST",
url: 'second.php',
dataType: 'JSON',
data: {"ajax-data": textboxvalue},
success: function(result)
{
$(".php_responce_here").html(result.message);
}
});
});
});
and return json string from PHP script
<?php
error_reporting(0);
require "config.php"; // configuration file holds the database info
$user_name = $_POST['ajax-data']; // textbox in the html
if ($user_name) {
$usernamecheck = mysql_query("SELECT count(*) FROM users WHERE username='$user_name'");
$check = mysql_fetch_row($usernamecheck);
if ($check[0] == 0) {
if ($user_name != "") {
if (strlen($user_name) > 25) {
$message = "You have reached the maximum limit";
} else {
$message = "User name is valid";
}
} else {
$message = "username is empty";
}
} else {
$message = "Username Already Taken";
}
echo json_encode(["message" => $message]);
}
?>
NOTE : mysql is deprecated. you should use mysqli or PDO
There are some mistakes in your code. check the below code. it should work.
<script>
$(document).ready(function () {
$("form").submit(function (event) {
var textboxvalue = $("#ajax-data").val();
$.ajax({
data: {ajaxdata: textboxvalue},
type: "POST",
url: 'second.php',
success: function (result)
{
$(".php_responce_here").html(result);
}
});
return false;
});
});
</script>
You can not create variable ajax-data with -.
PHP
$usernamecheck = mysql_query("SELECT * FROM users WHERE username='$user_name'");
$check = mysql_num_rows($usernamecheck);
you should use mysql_num_rows instead of mysql_fetch_row. it will auto calculate the rows.
Check working example
Empty page? Nothing prints out?
<?php
error_reporting(-1);
ini_set('display_errors', 1);
require "config.php";// configuration file holds the database info
if(isset($username = $_POST['ajax-data'])){
if($l = strlen($username) <= 25 && $l > 2){
$sql = "SELECT * FROM users WHERE username='$username'"; // wide open for SQL injections. use mysqli or PDO instead.
if($rsl = mysql_query($sql) != false){ // ALWAYS verify if your query's ran successfully.
if(mysql_num_rows($rsl) != 0){
echo 'Username already exists';
} else {
echo 'Username is available';
}
} else {
echo 'Query failed: ' . mysql_error();
}
} else {
echo $l > 25 ? 'Reached limit' : 'Needs to be longer';
}
} else {
echo "post['ajax-data'] not set<\br>";
print_r($_POST);
}
?>
Then there is your Javascript code that I have questions on. Yet you have a submit button but you want to check if its valid upon change?
$(document).ready(function(){
$("#user_form").submit(function(event){
event.preventDefault();
$.ajax({
url: "second.php",
type: "post",
data: $(this).serialize(),
success: function(result){
$(".php_responce_here").html(result);
}
});
});
});​

How to define an element with a a sql row id usng JSON encoded data

I'm using jQuery AJAX to process form data, the PHP side of it should delete two files on the server and then the SQL row in the database (for the id that was sent to it). The element containing the SQL row should then change color, move up, delete and the next SQL rows move into its place. The animation stuff occurs in the beforeSend and success functions of the ajax callback.
This script is not working, when user clicks button, the page url changes to that of the php script but the item and files do not get deleted either on the server or in the database. Nor does any of the animation occur.
This is my first time using jQuery ajax, I think there is a problem with how I define the element during the call back. Any help would be great:
js
$("document").ready(function(){
$(".delform").submit(function(){
data = $(this).serialize() + "&" + $.param(data);
if (confirm("Are you sure you want to delete this listing?")) {
$.ajax({
type: "POST",
dataType: "json",
url: "delete_list.php",
data: data,
beforeSend: function() {
$( "#" + data["idc"] ).animate({'backgroundColor':'#fb6c6c'},600);
},
success: function() {
$( "#" + data["idc"] ).slideUp(600,function() {
$( "#" + data["idc"] ).remove();
});
}
});
return false;
}
});
});
php
if (isset($_POST["id"]))
{
$idc = $_POST["id"];
if (isset($_POST["ad_link"]) && !empty($_POST["ad_link"]))
{
$ad_linkd=$_POST["ad_link"];
unlink($ad_linkd);
}
if (isset($_POST["listing_img"]) && !empty($_POST["listing_img"]))
{
$listing_imgd=$_POST["listing_img"];
unlink($listing_imgd);
}
try {
require('../dbcon2.php');
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "DELETE FROM listings WHERE id = $idc";
$conn->exec($sql);
}
catch (PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
echo json_encode($idc);
}
html
<div id="record-<?php echo $id; ?>">
*bunch of stuff*
<form method="post" class="delform">
<input name="id" type="hidden" id="id" value="<?php echo $id; ?>" />
<input name="ad_link" type="hidden" id="ad_link" value="<?php echo $ad_link; ?>" />
<input name="listing_img" type="hidden" id="listing_img" value="<?php echo $listing_img; ?>" />
<button type="submit">Delete</button>
</form>
</div>
You should fix your php code like this
try {
require('../dbcon2.php');
// It's better, if you will going to use MySQL DB, use the class designed to connect with it.
$conn = mysqli_connect("Servername", "usernameDB", "PasswordDB", "NameDB");
$sql = "DELETE FROM listings WHERE id = $idc";
mysqli_query($conn, $sql);
// you have to create a asociative array for a better control
$data = array("success" => true, "idc" => $idc);
// and you have to encode the data and also exit the code.
exit(json_encode($data));
} catch (Exception $e) {
// you have to create a asociative array for a better control
$data = array("success" => false, "sentence" => $sql, "error" => $e.getMessage());
// and you have to encode the data and also exit the code.
exit(json_encode($data));
}
Now in you JS code Ajax change to this.
$.ajax({
type: "POST",
dataType: "json",
url: "delete_list.php",
data: data,
beforeSend: function() {
$( "#" + data["idc"] ).animate({'backgroundColor':'#fb6c6c'},600);
},
success: function(response) {
// the variable response is the data returned from 'delete_list.php' the JSON
// now validate if the data returned run well
if (response.success) {
$( "#" + response.idc ).slideUp(600,function() {
$( "#" + response.idc ).remove();
});
} else {
console.log("An error has ocurred: sentence: " + response.sentence + "error: " + response.error);
}
},
// add a handler to error cases.
error: function() {
alert("An Error has ocurred contacting with the server. Sorry");
}
});

AJAX form submission with php and jquery

I have looked at everything on here that I can find and I just can't figure out why I cannot perfect this code. What I am trying to do is allow users to delete something that they posted on my site without doing a page refresh. The form is going to be passed to a php file that will modify my MySQL DB. I am new to ajax and have only messed around with PHP for a short time as well.
form:
<form class='status_feedback' id='delete_status' onsubmit='delete_status()' action=''>
<input type='hidden' name='status_id' id='status_id' value='$status_id'/>
<input type='submit' value='X'/>
</form>
delete_status()
function delete_status(){
$.ajax({
type: "POST",
url: "/scripts/home/php/delete_status.php/",
data: status_id,
success: function() {
//display message back to user here
}
});
return false;
}
delete_status.php
<?php
$con=mysqli_connect("localhost","USER","PASSWORD","DB");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$status_id = $_POST['status_id'];
mysqli_query($con,"UPDATE status SET visibility = 'hidden' WHERE id = $status_id");
?>
at this point, all that happens when I strike the delete_status() function is my page refreshes and adds ?status_id=194 (when I click on status #194) to the end or my url.
Any help would be awesome. I have been researching for several days.
Change your HTML, Ajax and php a little.
HTML
Add this code:
<body>
<form class='status_feedback' id='delete_status' >
<input type='hidden' name='status_id' id='status_id' value='$status_id'/>
<input type='button' id='x_submit' value='X' />
</form>
<script>
$('#x_submit').on("click",function(){
var status_id= $('#status_id').val();
//Delete the alert message if you want.
alert("Check your status id :"+status_id);
$.ajax({
type: "GET",
url: "/scripts/home/php/delete_status.php?",
data: {status_id:status_id},
dataType:'JSON',
success: function(json) {
//display message back to user here
alert(json[0].response);
}
});
});
</script>
PHP:
<?php
header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Methods: GET, POST');
header('Content-type: application/json');
$con=mysql_connect("localhost","USER","PASSWORD","DB");
// Check connection
if (mysql_connect_errno())
{
echo "Failed to connect to MySQL: " . mysql_connect_error();
}
$status_id = $_GET['status_id'];
$result = mysql_query("UPDATE status SET visibility = 'hidden'
WHERE id = '$status_id'");
if(! $result )
{
$data[]=array('response'=>"Unable to insert!");
}
else
{
$data[]=array('response'=>"Data successfully inserted into the database!");
}
$json_encode = json_encode($data);
print("$json_encode");
?>
Hope it will work.
You are not cancelling the form submission
onsubmit='delete_status()'
needs to be
onsubmit='return delete_status()'
and data: status_id, looks wrong unless you have a variable defined somewhere else

Categories

Resources