Javascript/jquery ajax request - javascript

I have a problem with this Ajax request, it causes error during the call, it is not shown in console nor compiler.
Javascript code:
jQuery(document).ready(function(){
jQuery.get({
url: "https://nonsoloalimentatori.it/tools/download-center/index.php?sku="+sku,
dataType: "jsonp",
cache: true,
success: function(){
console.log("success");
},
error: function(){
console.log("error");
}
}).done(function(){
console.log("here");
})
})
PHP:
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Credentials:');
header('Content-Type: application/json');
function searchJson($sku){
$array = [];
$json = file_get_contents('./list.json'); //read the file contente
$json_data = json_decode($json,true); //creating the json objectt
$n_elementi = count($json_data); //count the number of object element
for ($mul = 0; $mul < $n_elementi; ++$mul){ //for every element it is
searched the sku
if($json_data[$mul]["sku"] == $sku)//and it is compared to the sku
given by user
{
array_push($array,$json_data[$mul]);//if it is true the element
is added to array
}
}
return $array; //it is returned
}
if(isset($_GET['sku'])){
$result=searchJson($_GET['sku']);
echo json_encode($result, JSON_PRETTY_PRINT);
}

On jsonp response from the server side, jquery expects it to be under a callback function.
Please use the following code to output the server response:
$callback_function_name = !empty($_GET['callback'])? $_GET['callback'] : 'callback';
echo $callback_function_name.'('.json_encode($result, JSON_PRETTY_PRINT).')';
Reason for the callback function is: cross domain ajax call is not allowed in javascript, so in jsonp the url is loaded the way we load a js script file(you can add script from different domains in your site). The loaded script is then evaluated. If plain data is printed, it does nothing. So it is passed to a callback function registered by the caller JS to process.
You can set your own callback function too by setting:
jsonp : "custom_callback_function_name"
inside the ajax function as a parameter.
In that case your server side output should be like:
custom_callback_function_name({...json_data...});

Related

admin-ajax returning 0 - not submitting form data to db

I'm trying to send form data to a table called attendants. I have the form, the AJAX and query created, but when trying to test (when submitting the form), I see a POST http://localhost/rsvp/wp-admin/admin-ajax.php 400 (Bad Request) error on console.
Unsure what's causing this as when I run a console.log(ajaxurl); the URL it returns is http://localhost/rsvp/wp-admin/admin-ajax.php which is correct.
Unsure what's happening here?
EDIT: I've recently discovered that http://localhost/rsvp/wp-admin/admin-ajax.php returns 0.
form.php (Folder Path: rsvp > template-parts > parts > form.php) :
<div class="form sectionPadding" id="rsvp-form">
<form id="rsvpForm" method="post">
<?php get_template_part('template-parts/snippets/form-step-1'); ?>
<?php get_template_part('template-parts/snippets/form-step-2'); ?>
</form>
</div>
<script type="text/javascript">
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
</script>
form.js (form.js compiles into theme.min.js. The path to theme.min.js is rsvp > assets > build > js > theme.min.js) :
jQuery('#rsvpForm').on('submit', function(e) {
e.preventDefault();
jQuery.ajax({
action: 'send_to_db',
dataType: "text",
type: "post",
data: $('form').serialize(),
url: ajaxurl,
success: function(data) {
console.log(data);
},
error: function() {
console.log("Error");
}
});
});
functions.php
add_action("wp_ajax_send_to_db", "send_to_db");
add_action("wp_ajax_nopriv_send_to_db", "send_to_db");
function send_to_db(){
if (isset($_POST['submit'])) {
global $wpdb;
$first_name = $_POST['fname'];
$table_name = $wpdb->prefix . "attendants";
$row_result = $wpdb->query("INSERT INTO $table_name (first_name) VALUES ('$first_name')" );
if ($row_result == 1){
echo "submitted";
} else{
echo "error";
}
die();
}
}
To summarize, my folder structure is:
rsvp
assets
build
js
theme.min.js
template-parts
parts
form
form.php
form.js
functions.php
EDIT: I've recently discovered that
http://localhost/rsvp/wp-admin/admin-ajax.php returns 0.
That's indeed the expected return value when the request (URL) doesn't contain the AJAX action name. Additionally, the HTTP response status would also be a 400 Bad Request which basically means "missing action name" or "there's no callback registered for that action".
And in your case, it seems that your AJAX script is not sending the AJAX action.
Because in your form.js script, the action parameter should be in the data — and as far as I know, jQuery.ajax() doesn't have a action property:
jQuery.ajax({
action: 'send_to_db', // this should be in 'data'
...
data: $('form').serialize(),
...
});
So you can do data: $('form').serialize() + '&action=send_to_db' like so:
jQuery.ajax({
...
data: $('form').serialize() + '&action=send_to_db',
...
});
That way, WordPress would recognize the AJAX action (via $_REQUEST['action']) and then run the proper AJAX handler / PHP callback, which is send_to_db() in your case.
And you can confirm if your AJAX callback is registered properly by visiting /wp-admin/admin-ajax.php?action=send_to_db — are you still seeing a 0?
Update
If the HTTP response status is no longer 400 (where it should now be 200), then it means your AJAX request is sending an action (send_to_db in your case) and that there's a PHP callback registered for that AJAX action (wp_ajax_send_to_db / wp_ajax_nopriv_send_to_db).
But because your callback is only doing something when the POST variable submit is set, then if your AJAX request data doesn't include that, the response would still be a 0.
If you want to avoid that, then you can do something like so:
function send_to_db() {
if ( isset( $_POST['submit'] ) ) {
// ... your code here.
//die();
} else {
echo 'Invalid request!';
}
wp_die(); // It's recommended to always call this to end an AJAX request,
// but die() is OK, too.
}
And with that, when you manually go to /wp-admin/admin-ajax.php?action=send_to_db (i.e. without sending any POST data), you'd see Invalid request! on the page. window.fetch( '/wp-admin/admin-ajax.php?action=send_to_db' ) would even receive that same response.
So now that the error 400 is gone, you just need to make sure your AJAX request is sending the proper data and that your PHP callback is working (or doing what it needs to do). And on Chrome, you can easily inspect the request and response data, headers, etc. by opening the developer tools and go to the Network → XHR tab and simply click on the relevant request.
Your SQL query is highly insecure and I strongly suggest you to use wpdb::prepare() to prepare the query for safe execution:
//$row_result = $wpdb->query("INSERT INTO $table_name (first_name) VALUES ('$first_name')" );
$query = $wpdb->prepare(
"INSERT INTO $table_name (first_name) VALUES (%s)",
sanitize_text_field( $first_name )
);
$row_result = $wpdb->query( $query );
Alternatively, for inserting a single database row/entry, you can just use wpdb::insert():
$row_result = $wpdb->insert( $table_name, array(
'first_name' => sanitize_text_field( $first_name ),
) );
And I have actually tested your original PHP callback, and it worked, so long as the request data are good. :)

How to get response from PHP server asynchronously

First of all I know that there are many questions already regarding this.After reading all answers and trying it out ..but none of them worked.So I'm uploading a question here.Please don't delete it.
So,I created a html file with a form and then sent the form data using ajax jQuery to PHP file as follows.
$("#form-id").submit(function e() {
e.preventDefault();
var sdata=("#text_feild").val();
$.ajax({
url:"filename.php",
type:"POST",
data:sdata
});
//display the message sent by PHP
/*Use the data sent by PHP to perform
different function*/
Now I want PHP to send a message to js or html or anything else.Also, I want PHP to send some Boolean data which I will be using to perform some function.
If you want to send multiple data then you can do this by using array and send them json encoded and you will receive data in "success" callback function of ajax call
consider below example
ajax call
$("#form-id").submit(function e() {
e.preventDefault();
var sdata=("#text_feild").val();
$.ajax({
url:"filename.php",
type:"POST",
data:sdata,
async: true,
dataType: 'json',
success: function(data) {
console.log(data); // check result in console
$('#result').html((data.content) ? (data.content) : '???');
$('#result').prop('title', data.title);
$('#jsonstring').html('Json object: '+JSON.stringify(data));
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
});
<?php
$result = array(
'title' => 'Title',
'status' => 0,
);
echo json_encode($result);
?>
You can use the powerful pure javascript browser native fetch api.
To retrieve text/html.
fetch("https://api.github.com/")
.then(function(response) { return response.text() })
.then(function(text) {
console.log(text)
})
To retrieve json.
fetch("https://www.reddit.com/.json").then(v => v.json()).then((function(v){
syn = JSON.stringify(v)
main.innerHTML += syn
})
)
<div id="main">
Server side the base of a json api would be:
if ($_GET["myapi"] != ""){
header('Content-Type: application/json');
header("Access-Control-Allow-Origin: *");
echo json_encode(["Hello","World"]);
exit;
}
Calling: mysite/?myapi=whatever
Output: ["Hello","World"], with a json header, and CORS enabled.
Learn more about javascript promise(s)

Update php variable after success ajax call

I need to change a php variable after success ajax call. How do I do this?
I have a function that update path name directory in database and directory. So, I have a php variable in the beginning of page that's get the path of a file. This is called $final_path.
<?php
$path_directory = trim($pathDAO->path_dir($id_pag)[0]->path);
$final_path = trim('http://www.test.com/content/'.$path_directory);
?>
I put a hidden div in html:
<div id="dir_path" hidden="true"><?php echo $final_path; ?></div>
So, when you change the name of directory, I call an ajax function as below.
Notice after success, the php variable should be updated, but it is not happened.
$.ajax({
type:'POST',
url: 'change_name.php',
data: {id: uid, name: uname},
dataType: 'html',
success: function (data) {
var data_path = data.split("||");
var result = $.trim(data_path[0]);
var result_a = $.trim(data_path[1]);
if(result === "success") {
document.getElementById("dir_path").value = result_a;
document.getElementById("dir_path").innerHTML = result_a;
}
});
return false;
In Ajax function, I update the path name and return the result (success or fail) and the new path directory.
$success = $updatePath ->update($_POST['id'], $_POST['name']);
$path_directory = trim($pathDAO->path_dir($_POST['id'])[0]->path);
$path_dir = trim('http://www.test.com/content/'.$caminho_diretorio);
$result = $success.'||'.$path_dir;
echo $result;
That's work well. But the variable $final_path haven't updated.
What am I doing wrong?
Your $final_path variable can't be updated because the execution of the php page is already done at this point. PHP variables are not kept in memory after the server has finished processing the page.
If you need to do further processing on the server-side with this value, then you need to either store it in user-session or keep the value that you got in the resulting ajax call and send it as POST data when you call your next php page.

How to make a synchronous GET request in JavaScript?

JS code:
function saveCategories(i){
var categoriesList=JSON.parse(localStorage.getItem("categoriesList"));
var code=localStorage.getItem("gameCode");
if(i == categoriesList.length)
return;
var categoryName=categoriesList[i]['name'];
var items=categoriesList[i]['items'];
$.get('http://localhost:8080/yourfolder/newCategory.php',{GameCode:code,items:items,CategoryName:categoryName},function(resp)
{
saveCategories(i+1);
});
}
PHP code:
<?php
header("Access-Control-Allow-Origin");
$host="127.0.0.1";
$user="root";
$pass="password";
$databaseName="games";
$con=mysql_connect($host,$user,$pass,$databaseName);
if(!$con)
{
die("Connection failed: ".mysqli_connect_error());
}
$code=$_GET["GameCode"];
$name=$_GET["CategoryName"];
$items=$_GET["items"];
$data=array();
foreach($items as $item)
$data[]=addcslashes($item);
$data=implode(",",$data);
$sql="INSERT INTO games.categories(code,name,items) VALUES ('$code','$name','$data')";
$result=mysql_query($sql,$con);
echo $result;
?>
The php file (newCategory.php) should get code, category name and category items and insert them to MYSQL db.
The saveCategories recursive function should get the newCategory.php file for each category (in index i), but for some reason, it proceed to the next iteration without getting a result from the first GET request before.
The unwanted result is that the first category in index 0 is not saved in the MYSQL db.
use async: false in your data
example:
$.ajax({
url : "/your url",
type : "get",
async: false,
success : function(userStatus) {
//your logic
},
error: function() {
}
});
referring to this answer you can specify the asynchronous option to be false to get a synchronous Ajax request using jquery. You just need to specify
{async:false}
this article shows how to do it using a XMLHttpRequest().

Ajax data parse

I have a page with comments. By ajax, send a request to php page by. Php then scans the database... In general the standard logical operations. In any case, I meet php
echo '<script>show_info("my_text")</script>';
(show_info - js function which toggle info div and it displays my text).
And if all is well DB will transmit
echo 'ok';
My ajax success
success: function (data) {
if (data == "ok") {
document.write ("It's work!");
};
}
But unfortunately it does not work.
Maybe it is necessary somehow break the data into two parts, script and other text.
You're sending out the response straight away to the server with echo '<script>show_info("my_text")</script>'; as a response. because of this, data won't evaluate to 'ok'.
Instead, you should send back an array:
$ret = array(
'script' => 'show_info("my_text")',
'status' => 'ok'
);
echo json_encode($ret); // <--this should be done after all processing
Then in the ajax function you need to add the dataType parameter
$.ajax({
//etc
dataType: 'json',
success: function(data){
if(data.status == 'ok'){
eval(data.script);
}
}
});

Categories

Resources