jQuery Ajax is not getting posted to a PHP file - javascript

I am new to AJAX so I know there could be a silly mistake in my code but anyways I will go ahead.
I have a function created that is called when a button is clicked. The function calls .ajax() method of jquery. I send the data to a file named 'delete_post.php`.
HTML:
<button class="btn btn-primary" onclick="deletePost(<?php echo $_GET["id"]; ?>);">Yes</button>
The above code works.
JS:
function deletePost(postid) {
$.ajax({
type: 'post',
url: "delete_post.php?id="+postid,
success: function(data) {
if(data.error == true) console.log('error');
else console.log('problem?');
}
});
}
The above code is calling the .ajax() function but is not logging 'problem?' into the console.
Here's the PHP file:
<?php
require_once '...';
if(isset($_GET["id"])) {
$id = $_GET["id"];
echo "YEAH!";
} else {
header("location: index.php");
}
?>
What's the issue and how can I fix it?

as we discussed in the chat side, you can use it like this:
JS:
function deletePost(postid) {
$.post('delete_post.php', {id : postid}, function(data){
console.log(data);
}, 'json');
}
PHP:
<?php
require_once '...';
if(isset($_POST["id"])) {
$data['res'] = 'yes';
echo json_encode($data);
} else {
header("location: index.php");
}
?>

There is an escape issue in the following part:
onclick="deletePost(<?php echo $_GET["id"]; ?>);"
It must be as below:
onclick="deletePost(<?php echo $_GET['id']; ?>);"
And, you are echoing 'YEAH!', so the if condition should be:
if(data == 'YEAH!')

Here is your working code, In your AJAX you are doing "POST" and in your PHP file your using "GET".
trigger.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="jquery-1.7.1.min.js"></script>
<script>
function deletePost(postid) {
$.ajax({
type: 'GET',
url: "http://localhost/overflow/delete_post.php?id="+postid,
success: function(data) {
console.log('success:'+data);
}, error: function(xhr, status, error){
console.log(xhr.responseText);
}
});
}
</script>
</head>
<body>
<button class="btn btn-primary" onclick="deletePost(9); return false;">Yes</button>
</body>
</html>
delete_post.php
<?php
//require_once '...';
if(isset($_GET["id"])) {
$id = $_GET["id"];
echo "YEAH!";
//do something
} else {
// header("location: index.php");
echo "not set";
}
?>
Try this and let us know your problem in detailed and clear. good luck

Related

Showing data and posted values separately in ajax post

i have a task which is about ajax post data and also ask the script to show data...I have 3 files.. HTML file perform an ajax to the php script, passwrapper.php and then include the another script to show all data in the json format on the console.log in the html file.. I implemented some ajax post values such as 'Abdullahlahlahlah' and 'Muslim' so that the passwrapper.php will receive those data and echo on the console separatley from the whole data... Developer said ajax cannot echo 2 times...... Is it totally impossible???? If there is no way, please tell me other options...
Requirement: Please do not modify the student.php as i want the that php script to echo all the data in json..
Modify the paswrapper.php and html file..
When i run the html file, the error states
Status Code: 200
ErrorThrown: SyntaxError: Unexpected token < in JSON at position 1634
jqXHR.responseText:
[{"student_id":"1","student_name":"Ashfur","student_gender":"F","student_age":"19","student_religion":"Muslim","student_course_id":"1"},{"student_id":"2","student_name":"Irfan","student_gender":"M","student_age":"17","student_religion":"Islam","student_course_id":"4"},{"student_id":"3","student_name":"Alice","student_gender":"F","student_age":"21","student_religion":"Chinese","student_course_id":"2"},{"student_id":"4","student_name":"Mohit","student_gender":"M","student_age":"20","student_religion":"Christian","student_course_id":"6"},{"student_id":"5","student_name":"Susy","student_gender":"F","student_age":"27","student_religion":"Chirstian","student_course_id":"5"},{"student_id":"6","student_name":"Ida","student_gender":"F","student_age":"23","student_religion":"Islam","student_course_id":"3"},{"student_id":"7","student_name":"Abdul","student_gender":"M","student_age":"22","student_religion":"Islam","student_course_id":"1"},{"student_id":"8","student_name":"Ernest","student_gender":"M","student_age":"25","student_religion":"Chinese","student_course_id":"4"},{"student_id":"9","student_name":"Wei Ling","student_gender":"F","student_age":"23","student_religion":"Chinese","student_course_id":"2"},{"student_id":"10","student_name":"Ashtae","student_gender":"M","student_age":"23","student_religion":"Islam","student_course_id":"4"},{"student_id":"11","student_name":"Jasmine","student_gender":"F","student_age":"23","student_religion":"Chinese","student_course_id":"2"},{"student_id":"65656","student_name":"yyyyty","student_gender":"F","student_age":"65","student_religion":"anything","student_course_id":"009090"}]
Also there is the posted values on the console.log which states LastRowname = Abdullahlahlahlah LastRowReligion = Muslim
HTML File
<html>
<head>
<script type="text/javascript" src="/Cesium-1.34/ThirdParty/jquery-1.11.3.min.js"></script>
</head>
<div id="results"</div>
<div id="resulte"</div>
<script type="text/javascript">
showData();
function showData()
{
$.ajax({
type: "post",
url: "passwrapper.php",
dataType: "json",
data: {
lastName: 'Abdullahlahlahlah',
lastReligion: 'Muslim',
},
success: function(data){
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert('An error occurred... Look at the console (F12 or Ctrl+Shift+I, Console tab) for more information!');
$('#resulte').html('<p>Status Code: '+jqXHR.status+'</p><p>ErrorThrown: ' + errorThrown + '</p><p>jqXHR.responseText:</p><div>'+jqXHR.responseText + '</div>');
console.log('jqXHR:');
console.log(jqXHR);
console.log('textStatus:');
console.log(textStatus);
console.log('errorThrown:');
console.log(errorThrown);
},
});
};
</script>
</body>
</html>
passwrapper.php
<?php
include 'student.php';
executePass();
receivePost();
function receivePost()
{
if ((!isset($_POST["lastName"])) and (!isset($_POST["lastReligion"])))
{
//do nothing
}
else
{
echo '<script>console.log("LastRowname = '.$_POST["lastName"].' LastRowReligion = '.$_POST["lastReligion"].'");</script>';
}
}
?>
student.php
<?php
function executePass()
{
$conn = mysqli_connect('localhost','root','netwitness') or die ("Could not connect database");
$db = mysqli_select_db($conn,'abdpractice') or die ('Could not select database');
$result = mysqli_query($conn,"select * from student");
$json_array = array();
while ($row = mysqli_fetch_assoc($result))
{
$json_array[] = $row;
}
echo json_encode($json_array);
}
?>
in my network tab
[{"student_id":"1","student_name":"Ashfur","student_gender":"F","student_age":"19","student_religion":"Muslim","student_course_id":"1"},{"student_id":"2","student_name":"Irfan","student_gender":"M","student_age":"17","student_religion":"Islam","student_course_id":"4"},{"student_id":"3","student_name":"Alice","student_gender":"F","student_age":"21","student_religion":"Chinese","student_course_id":"2"},{"student_id":"4","student_name":"Mohit","student_gender":"M","student_age":"20","student_religion":"Christian","student_course_id":"6"},{"student_id":"5","student_name":"Susy","student_gender":"F","student_age":"27","student_religion":"Chirstian","student_course_id":"5"},{"student_id":"6","student_name":"Ida","student_gender":"F","student_age":"23","student_religion":"Islam","student_course_id":"3"},{"student_id":"7","student_name":"Abdul","student_gender":"M","student_age":"22","student_religion":"Islam","student_course_id":"1"},{"student_id":"8","student_name":"Ernest","student_gender":"M","student_age":"25","student_religion":"Chinese","student_course_id":"4"},{"student_id":"9","student_name":"Wei Ling","student_gender":"F","student_age":"23","student_religion":"Chinese","student_course_id":"2"},{"student_id":"10","student_name":"Ashtae","student_gender":"M","student_age":"23","student_religion":"Islam","student_course_id":"4"},{"student_id":"11","student_name":"Jasmine","student_gender":"F","student_age":"23","student_religion":"Chinese","student_course_id":"2"},{"student_id":"65656","student_name":"yyyyty","student_gender":"F","student_age":"65","student_religion":"anything","student_course_id":"009090"}]<script>console.log("LastRowname = Abdullahlahlahlah LastRowReligion = Muslim");</script>
my requirement:
i want to echo all the data(except the posted values) on the html file.
i want to show the posted values on the console.log. it can either be in the passwrapper.php or html file..... Please help me....
ajax cannot echo 2 times;
1.student.php
while ($row = mysqli_fetch_assoc($result))
{
$json_array[] = $row;
}
//echo json_encode($json_array);
return $json_array;
2.passwrapper.php
<?php
include 'student.php';
$data['student_arr']=executePass();
$data['post_str']=receivePost();
echo json_encode($data);
function receivePost()
{
if ((!isset($_POST["lastName"])) and (!isset($_POST["lastReligion"])))
{
//do nothing
}
else
{
$post_str= 'LastRowname = '.$_POST["lastName"].' LastRowReligion = '.$_POST["lastReligion"].'';
return $post_str;
}
}
?>
3.html file
success: function(data){
console.log(data.post_str);
$('#results').text(JSON.stringify(data.student_arr));
},
passwapper.php
<?php
include 'student.php';
ob_start();
executePass();
$string = ob_get_contents();
ob_end_clean();
$data['student_arr']=json_decode($string);
$data['post_str']=receivePost();
echo json_encode($data);
function receivePost()
{
if ((!isset($_POST["lastName"])) and (!isset($_POST["lastReligion"])))
{
//do nothing
}
else
{
$post_str= 'LastRowname = '.$_POST["lastName"].' LastRowReligion = '.$_POST["lastReligion"].'';
return $post_str;
}
}
?>

Am i getting html and javascript code when using ajax to pass parameters to the function on onClick event (Ajaxing on the same page)

<html>
tables, textbox, buttons
</html>
<?php
//some php, sql stuff
echo "<td><input type='button' name='disable' value='Disable' onClick='disable($id);'/></td>";
if(isset($_POST['action']) && $_POST['action']=="delete")
{
if(isset($_POST['ID']) && !empty($_POST['ID']))
{
$id = $_POST['ID'];
echo "Id:".$id;
//Call to another function
die();
}
?>
<script>
function disable(id) {
jQuery.ajax({ type: 'Post',
url: '',
data: {action: 'delete', ID: id}
})
.done(function(data) {
alert("Data Saved: " + data);
location.reload();
});
}
</script>
Alert box is showing html code which is in HTML block and successful messages from php block. I don't need to show HTML code, only need to show successful messages. How to do that??? many thanks
The issue is that you need to respond to the ajax request before any html is sent to the browser and call exit; to stop the remaining page content from being sent as well. Something like this would work:
<?php
if(isset($_POST['action']) && $_POST['action']=='delete'){
// process request......
$id = $_POST['ID'];
echo "Id:".$id;
//Call to another function
exit; // stop the script here so it doesnt also return the html content of the page
}
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
tables, textbox, buttons
<?php
//some php, sql stuff
// note that $id is not defined where you try to use it here in your code, not sure what that's about....
echo "<td><input type='button' name='disable' value='Disable' onClick='disable($id);'/></td>";
?>
<script>
function disable(id) {
jQuery.ajax({ type: 'Post',
url: '',
data: {action: 'delete', ID: id}
})
.done(function(data) {
alert("Data Saved: " + data);
location.reload();
});
}
</script>
</body>
</html>

Run php file via jquery call in Wordpress

So I wish to replicate the following functionality in wordpress. Jquery calls a php file, which itself queries a mysql table, and returns the result encapsulated within an tag. How do I go about achieving this?:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript">
....
function initialize() {
....
feedData();
}
$(document).ready(function () { initialize(); });
function feedData() {
$(document).ready(function () {
$.ajax({
cache: false,
type: "POST",
async: false,
url: "page-gotw-search.php",
data:{"action=showcountries"},
success: function (data) {
$('#CountryList').append(data);
},
error: function (data, status, error) {
console.log(data);
console.log(status);
console.log(error);
}
});
});
}
</script>
<body>
<div style="width: 800px">
<div style="float: left">
<select id="CountryList" onchange="getRegion()" size="20"></select>
<select id="RegionList" size="20" onchange="getMap()"></select>
</div>
<div id="cityList" style="float: right"></div>
</div>
</body>
</html>
page-gotw-search.php
<?php
include_once("pdo_mysql.php");
pdo_connect("localhost","root","");
pdo_select_db("wpdb");
$action=$_POST["action"];
if($action=="showcountries"){
$showcountry = pdo_query("Select distinct meta_value from wp_usermeta where meta_key =?, pdo_real_escape_string('country_registration')");
if (!$showcountry) {
$message = 'Invalid query: ' . pdo_error() . "\n";
$message .= 'Whole query: ' . $showcountry;
die($message);
}else{
foreach($showcountry as $row){
echo '<option value=".$row[country_code].">.$row[country_name].</option>';
}
}
}
else if($action=="showregions"){
$country_id= $_POST["country_id"];
$showregion = pdo_query("Select region_code, region_name from regiontbl
WHERE country_id=?", pdo_real_escape_string($country_id));
if (!$showregion) {
$message = 'Invalid query: ' . pdo_error() . "\n";
$message .= 'Whole query: ' . $regionquery;
die($message);
}else{
foreach($showregion as $row){
echo '<option value=".$row[region_code].">.$row[region_name].</option>';
}
}
}
?>
Looks like you want to implement ajax into the wordpress.
I have a simple way to do this. Follow below given steps to use ajax calls in wordpress
add some code in footer.php
jQuery(‘#clickerid').change(function(){
var your_id = jQuery(‘#get_val').val();
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
jQuery.ajax({
cache: false,
type: 'POST',
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: ‘id='+ id + '&action=get_id',
success: function(data)
{
jQuery(‘#id').html(data);
}
});
});
Then use this ajax call into the functions.php
add_action( 'wp_ajax_get_your_action', 'prefix_ajax_get_your_action' );
add_action( 'wp_ajax_nopriv_get_your_action', 'prefix_ajax_get_your_action' );
function prefix_ajax_get_costofcare() {
// Do your php code used in ajax call and return it.
}
Ajax calls works via admin-ajax.php which is build in functionality provided by wordpress

Ajax and jQuery with PHP

I have this code which posts data using jQuery and ajax to itself.
<input type="button" id="butt" value="button11111111111111" >
<script>
$("#butt").on('click',function(e)
{
$.ajax(
{
type:'POST',
url:'test.php',
data:product_type:"cake"
});
});
</script>
<?php
if(isset($_POST['product_type']))
$abc=$_POST['product_type'];
if(isset($abc))
echo $abc;
?>
Now when I try to run this code.I do get the ok status inside the Network Console of Chrome but this code doesn't echo the output.
I simply want to display the result that has been passed by the ajax method.
I am new to ajax and jquery so i don't know much about how they work exactly but is it possible?
If yes, then how could i achieve that without actually refreshing the page?
Here is what I think you want, i.e. test.php is the source page AND the ajax page!
<?php
if(isset($_POST['product_type'])) {
Header("Content-type: text/plain; charset=utf-8");
$abc=$_POST['product_type'];
if(isset($abc)) {
echo $abc;
}
}
else {
?>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"> </script>
<input type="button" id="butt" value="button11111111111111" >
<script>
$("#butt").on('click',function(e) {
$.ajax({
type:'POST',
url:'test.php',
data: {
product_type:"cake"
},
success: function(data) {
alert('got ' + data);
}
});
});
</script>
</html>
<?php
}
?>

How to send data via ajax?

I'm trying to learn how does Ajax work and how I can send data by Ajax. I'm getting no error and nothing is being echoed.
index.html
<input id="name" type="text" /><input id="button" type="button" value="Load" />
<div id="feedback"></div>
<script type="text/javascript" src="../js/jquery.js"></script>
<script type="text/javascript" src="ajax.js"></script>
page.php
<?php
if (isset($_GE['name'])) {
$name = $_GET['name'];
}
?>
ajax.js
$('#button').click(function(){
var name = $('#name').val();
$.ajax({
url: 'page.php',
data: 'name='+name,
success: function(data){
$('#feedback').html(data);
}
});
});
I appreciate any help
You are missing an echo in your page php
<?php
if (isset($_GE['name'])) {
$name = $_GET['name'];
echo $name;
}
?>
also in your javascript send an object like this
data : { name : name}
should work
data : { name : 'John'}
you can check the success method is invoked or not invoked.
Also you need to echo something from php.
echo $name

Categories

Resources