AJAX POST group of form variables to PHP - javascript

I am trying to send a group of form parameters over to a PHP script for processing.
I've previously done something like this using $.post, but now I'm trying to get it done strictly by using $.ajax.
Here is the jQuery click event that is supposed to send all of the variables to the PHP script:
$('.searchSubmit').on('click', function()
{
var searchCriteria = {
import_bill: $('#import_bill').val(),
import_ramp: $('#import_ramp').val(),
import_delivery: $('#import_delivery').val(),
// few more form parameters
};
$.ajax({
url: 'api/railmbs.php', // process script
type: 'POST',
data: searchCriteria, // parameter group above
dataType: 'html' // had this set to json, but only got fail
success: function(data, textStatus, jqXHR)
{
console.log(data);
},
error: function(jqHHR, textStatus, errorThrown)
{
console.log('fail');
}
});
});
Here is the PHP script, called railmbs.php:
<?php
if(isset($_POST['searchCriteria']))
{
$value = $_POST['searchCriteria'];
$_SESSION['where'] = "";
$import_bill = mysqli_real_escape_string($dbc, trim($value['import_bill']));
$import_ramp = mysqli_real_escape_string($dbc, trim($value['import_ramp']));
$import_delivery = mysqli_real_escape_string($dbc, trim($value['import_delivery']));
echo $import_bill; // just trying to echo anything at this point
}
?>
Not sure what I am doing wrong. If I echo hello before the IF above, the console will output accordingly. But I cannot seem to get anything to echo from inside the IF.
Does anyone see my error?

You are not setting the "searchCriteria" variable.
Change this:
$('.searchSubmit').on('click', function()
{
var searchCriteria = {
import_bill: $('#import_bill').val(),
import_ramp: $('#import_ramp').val(),
import_delivery: $('#import_delivery').val(),
// few more form parameters
};
$.ajax({
url: 'api/railmbs.php', // process script
type: 'POST',
data: searchCriteria, // parameter group above
dataType: 'html' // had this set to json, but only got fail
success: function(data, textStatus, jqXHR)
{
console.log(data);
},
error: function(jqHHR, textStatus, errorThrown)
{
console.log('fail');
}
});
});
to:
$('.searchSubmit').on('click', function()
{
var data = {
searchCriteria: {
import_bill: $('#import_bill').val(),
import_ramp: $('#import_ramp').val(),
import_delivery: $('#import_delivery').val(),
// few more form parameters
}
};
$.ajax({
url: 'api/railmbs.php', // process script
type: 'POST',
data: data, // parameter group above
dataType: 'html' // had this set to json, but only got fail
success: function(data, textStatus, jqXHR)
{
console.log(data);
},
error: function(jqHHR, textStatus, errorThrown)
{
console.log('fail');
}
});

First of all. Why not to use $("form").serialize()? It would be much cleaner.
Secondary, you transfer data in root object, so to get you values, check $_POST array.
Instead of $value = $_POST['searchCriteria'] use $value = $_POST;.
This PHP code should work:
<?php
if(isset($_POST))
{
$_SESSION['where'] = "";
$import_bill = mysqli_real_escape_string($dbc, trim($_POST['import_bill']));
$import_ramp = mysqli_real_escape_string($dbc, trim($_POST['import_ramp']));
$import_delivery = mysqli_real_escape_string($dbc, trim($_POST['import_delivery']));
echo $import_bill; // just trying to echo anything at this point
}
?>
Or modify your js to send data in searchCriteria object, like this:
var searchCriteria = {
searchCriteria: {
import_bill: $('#import_bill').val(),
import_ramp: $('#import_ramp').val(),
import_delivery: $('#import_delivery').val(),
// few more form parameters
}};

You should check if you actually send post data using your browser developer tools or typing var_dump($_POST); at the beginning of your PHP script.
As far as i can see, you never actually set searchCriteria as post variable.
Currently your $_POST variable should contain the field import_bill, import_ramp and so on. Either change your if statement or your JavaScript object to {searchCriteria: {/*Your data here*/}.

Related

Send variable to php via ajax

I'm trying to send a input value to php via ajax but I can't seem to get this right. I'm trying to create a datatable based on the user input.
This is my code:
<input class="form-control" id="id1" type="text" name="id1">
My javascript code:
<script type="text/javascript">
$(document).ready(function() {
var oTable = $('#jsontable').dataTable(); //Initialize the datatable
$('#load').on('click',function(){
var user = $(this).attr('id');
if(user != '')
{
$.ajax({
url: 'response.php?method=fetchdata',
data: {url: $('#id1').val()},
dataType: 'json',
success: function(s){
console.log(s);
oTable.fnClearTable();
for(var i = 0; i < s.length; i++) {
oTable.fnAddData([
s[i][0],
s[i][1],
s[i][2],
s[i][3],
s[i][4],
s[i][5],
s[i][6],
s[i][7]
]);
} // End For
},
error: function(e){
console.log(e.responseText);
}
});
}
});
});
</script>
My php script:
<?php
$conn = pg_connect(...);
$id1 = $_POST["id1"];
$result = pg_query_params($conn, 'SELECT * FROM t WHERE id1 = $1 LIMIT 20', array($id1));
while($fetch = pg_fetch_row($result)) {
$output[] = array ($fetch[0],$fetch[1],$fetch[2],$fetch[3],$fetch[4],$fetch[5],$fetch[6],$fetch[7]);
}
echo json_encode($output);
?>
I don't know a lot of js but my php is correct i test it. So i guess the problem is in the javascript code.
The problem is, my datatable is not being created based on the user input.
Thank you!
change
data: {url: $('#id1').val()},
to:
type: 'POST',
data: {id1: $('#id1').val()},
However the problem might be bigger. You might not be getting the correct data from PHP. You can debug by adding the error option to your ajax() call, like this:
$.ajax({
url: 'response.php?method=fetchdata',
type: 'POST',
data: {id1: $('#id1').val()},
dataType: 'json',
success: function(s){
},
error: function (xhr, status, errorThrown) {
console.log(xhr.status);
console.log(xhr.responseText);
}
});
Then check your browser's Console for the output, this should give you some type of error message coming from PHP.
My assumption is that since you are using dataType: 'json', the ajax request expects JSON headers back, but PHP is sending HTML/Text. To fix, add the correct headers before echoing your JSON:
header('Content-Type: application/json');
echo json_encode($output);

how can I trigger javascript css action?

I have a memory game code, using javascript, php and css.
I would like to register somehow the event when the game is finished by php so that I can save the results in database.
In other words I would like to place php code inside <div id="player_won"> </div> and trigger that winning event properly.
css
#player_won{
display: none;
}
javascript
$(document).ready(function(){
$(document).bind("game_won", gameWon);
}
function gameWon(){
$.getJSON(document.location.href, {won: 1}, notifiedServerWin);
var $game_board = $("#game_board");
var $player_won = $("#player_won");
$game_board.hide();
$player_won.show();
$game_board = $player_won = null;
};
You'll want to create an ajax call that sends some information from the page and tells the php file below if the player has won or lost. After which you can deal with the logic needed for the player inside foo.php and send back Json to the success function inside the ajax call and update your page accordingly.
index
$(document).ready(function () {
//look for some kind of click below
$(document).on('click', '#SomeId', function () {
//Get the information you wish to send here
var foo = "test";
$.ajax({
url: "/foo.php",
type: 'POST',
cache: false,
data: {Info: foo},
dataType: 'json',
success: function (output, text, error)
{
//here is where you'll receive the son if successfully sent
if(ouput.answer === "yes"){
$("#player_won").show();
} else {
// Do something else
}
},
error: function (jqXHR, textStatus, errorThrown)
{
//Error handling for potential issues.
alert(textStatus + errorThrown + jqXHR);
}
})
})
});
foo.php
<?php
if(isset($_POST['Info'])){
//figure out if what was sent is correct here.
if($_POST['Info'] === "test"){
$data['answer'] = "yes";
echo json_encode($data);
exit;
} else {
// do something else
}
}
?>

AJAX in WordPress only returns 0

I'm trying to utilize WordPress's admin-ajax feature in order to build a dynamic admin panel option-set for a plugin. Essentially, once an option is selected from a dropdown (select/option menu), PHP functions will sort through and display more dropdown menus that fall under the dropdown above it. I began with a simple return that I was hoping to utilize later down the line, but I can't seem to get the text to print out without running into unidentified issues.
The AJAX I set up puts out a 200 status but the response never builds, and I'm left with 0 as my result. Here's the code:
JS/jQuery built into PHP function ajax-action()
$ = jQuery;
$('#platform').change(function(e) {
var data = {
action: 'action_cb',
type: 'POST',
dataType: 'json',
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(errorThrown);
},
success: function(response) {
$('#user_id').val(response);
}
};
$.ajax(ajaxurl, data, function(data) {
$('#user_id').val(data);
});
e.preventDefault();
});
PHP functions and add-actions
add_action('wp_ajax_action_cb','action_cb');
add_action('admin_footer','ajax_action');
function action_cb() { $platform = 'test'; echo json_encode($platform); wp_die(); };
My question is: how can I fix this and prevent it from continuing to happen? I'd like to return the actual results and not 0.
As per the wordpress documentation:
https://codex.wordpress.org/AJAX_in_Plugins (Reference "Error Return Values")
A 0 is returned when the Wordpress action does not match a WordPress hook defined with add_action('wp_ajax_(action)',....)
Things to check:
Where are you defining your add_action('wp_ajax_action_cb','action_cb');?
Specifically, what portion of your plugin code?
Are you logged into wordpress? You mentioned the admin area, so I'm assuming so, but if you are not, you must use add_action('wp_ajax_nopriv_{action}', ....)
Additionally, you didn't share the function this is tied to:
add_action('admin_footer','ajax_action');
And lastly, why are you using "json" as the data type? If you are trying to echo straight HTML, change data type to 'html'. Then you can echo directly on to page (or as a value as you are doing). Currently, you are trying to echo a JSON object as a value in the form...
So your code would look like so:
function action_cb() { $platform = 'test'; echo $platform; p_die(); };
...and your AJAX could be:
<script type = "text/javascript">
jQuery.ajax({
url: ajaxurl,
type: 'post',
data: {'action' : 'action_cb'},
success: function (data) {
if (data != '0' && data != '-1') {
{YOUR SUCCESS CODE}
} else {
{ANY ERROR HANDLING}
}
},
dataType: 'html'
});
</script>
Try This:
<script>
$ = jQuery;
$('#platform').change(function(e) {
var data = {
data: {'action' : 'action_cb'},
type: 'POST',
dataType: 'json',
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(errorThrown);
},
success: function(response) {
$('#user_id').val(response);
}
};
$.ajax(ajaxurl, data, function(data) {
$('#user_id').val(data);
});
e.preventDefault();
});
</script>
Probably you need to add
add_action('wp_ajax_nopriv_action_cb', 'action_cb');
https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)
just make small change in your AJAX. I am assuming you're logged in as admin.
replace action in data object with data:"action=action_cb",
var data = {
data:"action=action_cb",
type: 'POST',
dataType: 'json',
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(errorThrown);
},
success: function(response) {
$('#user_id').val(response);
}
};
$.ajax(ajaxurl,data,function(data){
$('#user_id').val(data);
});
To prevent WP adding zero into response i always using die(); insted of wp_die();
and registering function:
add_action( 'wp_ajax_action_cb', 'action_cb_init' );
add_action( 'wp_ajax_nopriv_action_cb', 'action_cb_init' );
function action_cb_init() {
}
When calling to function with AJAX use action: 'action_cb'
Hope this helps. I have already explained standard way of using ajax in wp.
Wordpress: Passing data to a page using Ajax
Ok, I have been recreating your code now in my own project and noticed that the javascript you shared returned the ajax-object and not the results. So what I come up with is a bit rewriting, but is worked fine when I tried it.
$j = jQuery.noConflict();
$j('#platform').change(function(e) {
$j.ajax({
url: ajaxurl,
type: 'POST',
dataType: 'json',
data: {
action: 'action_cb',
}
}).done(function( data ) {
// When ajax-request is done.
if(data) {
$j('#user_id').val(data);
} else {
// If 0
}
}).fail(function(XMLHttpRequest, textStatus, errorThrown) {
// If ajax failed
console.log(errorThrown);
});
e.preventDefault();
});
I hope the comments explain good enough how it is working. Note how I'm using $j instead of just $ for the jQuery.noConflict mode.
For those by the "Load More" problem.
Normally "0" is used instead of false.
I found such a solution.
So that 0 does not come. Try this code with false.
PHP
ob_start(); // start the buffer to capture the output of the template
get_template_part('contents/content_general');
$getPosts[] = ob_get_contents(); // pass the output to variable
ob_end_clean(); // clear the buffer
if( $read == $articles->found_posts )
$getPosts[] = false;
JS
if( posts[i] == false )
$(".load_more_button").fadeOut();

Returning values from a PHP script for an AJAX method: What am I doing wrong here?

From everything I've read on the internet, the way of returning HTML, JSON, etc., from a PHP script is simply by echoing it. I can't get it to work, however.
My JS is
jQuery('#new-member').submit(
function()
{
var formUrl = jQuery(this).attr('action');
var formMethod = jQuery(this).attr('method');
var postData = jQuery(this).serializeArray();
console.log(postData); // test for now
jQuery.ajax(
{
url: formUrl,
type: formMethod,
dataType: 'json',
data: postData,
success: function(retmsg)
{
alert(retmsg); // test for now
},
error: function()
{
alert("error"); // test for now
}
}
);
return false;
}
);
and I've verified that it is correctly calling my PHP script, which as a test is simply
<?php
echo "Yo, dawg.";
?>
but all that does is open "Yo, dawg." in a new page. The expected behavior is for it to alert that message on the same page I was on. What am I missing here?

How to avoid 500 Internal Server Error if a JS session variable null

I created this script to read from various web sources. This script updates all notifications (mail, post, friends) and their own drop-down window's details and also two side update bars together. I used this script in my top manu.php page.
This script is working well for login user.
Now I pass a session id variable with JavaScript var uid = '<? echo $session->id; ?>'; So when a user is not logged in, my browser console displays 500 Internal Server Error because here the session has no ID so it passes uid= ''
How do I overcome this problem?
Here is my JavaScript script:
var uid = '<? echo $session->id; ?>';
function addmailno(type, msg){
//Do something for display mail/friend/post notification
}
function addmailup(type, msg){
//Do something for display mail/post/friend drop-down.
}
function addside(type, msg){
//Do something for display all friend/new post in side bar.
}
function waitFormailno(){
$.ajax({
type: "GET",
url: "serverforupandside.php",
cache: false,
async : false,
dataType : 'json',
data: "uid="+ uid,
timeout:15000,
success: function(data){
addmailno("MyDivClass", data);
addmailup("MyDivClass", data);
addside("MyDivId", data);
setTimeout(waitFormailno, 15000);
},
error: function(){
setTimeout(waitFormailno, 15000);
}
});
}
$(document).ready(function(){
waitFormailno();
});
serverforupandside.php
<?php
include("db.php");
include_once("mysession.php");
while (true) {
if($_GET['uid']){
global $dbh;
//All php query is here one after one
//Output is here by data
$data = array();
$data['upmail'] = $upmail;
$data['upfollow'] = $upfollow;
$data['uppost'] = $uppost;
// etc all
if (!empty($data)) {
echo json_encode($data);
flush();
mysqli_close($dbh);
}
}
mysqli_close($dbh);
}
?>
Your Javascript code should be modified to:
function waitFormailno(){
$.ajax({
type: "GET",
url: "serverforupandside.php",
cache: false,
async : false,
dataType : 'json',
data: "uid="+ uid,
timeout:15000,
success: function(data){
addmailno("MyDivClass", data);
addmailup("MyDivClass", data);
addside("MyDivId", data);
}
});
}
$(document).ready(function(){
setInterval(waitFormailno, 15000); // calls a function or evaluates an expression at specified intervals (in milliseconds)
});
PHP Code:
<?php
include("db.php");
include_once("mysession.php");
if (!empty($_GET['uid'])) {
global $dbh;
//All php query is here one after one
//Output is here by data
$data = array();
$data['upmail'] = $upmail;
$data['upfollow'] = $upfollow;
$data['uppost'] = $uppost;
// etc all
if (!empty($data)) {
echo json_encode($data);
}
}
Also, you should add validations before filling $data array.

Categories