Using jquery ajax vs native xhr - javascript

I'm not too familiar with JQuery, and I'm trying to make a post request using jquery ajax.
I was previously using xhr, and I'm not totally sure if I'm reworking it correctly. If someone could give me some feedback, that would be greatly appreciated!
Here is my original code with xhr:
j("#saveButton").click(function() {
var ID = j(".selected-list")[0].getAttribute('id');
var subject = j('input').val();
var blurb = j("#blurb_stream").val();
var date = j('datepicker').val();
if(blurb.length != '' && ID != undefined && subject.length != ''){
xhr.open("POST", envUrl + "streams/" + ID + "/touches?subject=" + subject + "&body=" + blurb + "&schedule_on=" + date, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
console.log('saved!');
} else {
alert('not working');
}
}
xhr.send();
}
});
Here is my adjusted code using ajax:
j("#saveButton").click(function() {
var ID = j(".selected-list")[0].getAttribute('id');
var subject = j('input').val();
var blurb = j("#blurb_stream").val();
var date = j('datepicker').val();
var data = new FormData();
data.append("date", "date");
data.append("ID", "ID");
data.append("subject", "subject");
data.append("blurb", "blurb");
// check this!
if(blurb.length != '' && ID != undefined && subject.length != ''){
j.ajax({
url: 'envUrl + "streams/" + ID + "/touches?subject=" + subject + "&body=" + blurb + "&schedule_on=" + date',
type: "POST",
data: data,
success: function(){
alert(1);
}
});
}
}

Way too complex. With JQuery AJAX is slim. Here I replace all data.append() with an inline object. I've also removed the query string because it's the same information as in the data block. I've also fixed the URL line, which has some misplaced quotes:
j.ajax({
url: envUrl + "streams/" + ID + "/touches",
type: "POST",
data: { "date": date, "ID": ID, "subject": subject, "blurb": blurb },
success: function () {
alert(1);
}
});
From here you can replace the date/ID/subject/blurb with your fetch methods. Example:
j.ajax({
url: envUrl + "streams/" + ID + "/touches",
type: "POST",
data: {
"date": j('datepicker').val(),
"ID": j(".selected-list")[0].getAttribute('id'),
"subject": j('input').val(),
"blurb": j("#blurb_stream").val()
},
success: function () {
alert(1);
}
});
The whole script is now:
j("#saveButton").click(function () {
j.ajax({
url: envUrl + "streams/" + ID + "/touches",
type: "POST",
data: {
"date": j('datepicker').val(),
"ID": j(".selected-list")[0].getAttribute('id'),
"subject": j('input').val(),
"blurb": j("#blurb_stream").val()
},
success: function () {
alert(1);
}
});
});

You have a mistake in your url param, try taking the single quotes out:
j.ajax({
url: envUrl + "streams/" + ID + "/touches?subject=" + subject + "&body=" + blurb + "&schedule_on=" + date,
type: "POST",
data: data,
success: function(){
alert(1);
}
});
Also, a little bit of background on using HTTP requests.
In general there are two primary ways of passing data to the server. One method is via URL params, in this case it would be a GET request, and you pass the params on the query string (like you've done in your URL).
The other way is via POST. With the POST verb, you pass data in the body of the request in a delimited format. In this case, you would provide the ajax call with the data: param. Doing both is redundant.
Following best practices, you shouldn't use a GET request to modify data (except in some rare circumstances). If you're modifying data, you should use a POST, PUT, PATCH or other verb.

Related

Jquery-ajax doesn't succeed

I am quite new to to ajax, just learning it, and made a simple page on localhost to test gets and posts from/to json file in the same folder.
While GET is working smoothly, I cannot figure out, why post doesn't happen if I click the button I assigned this function to.
Pls take a look into my code and help.
element = $("#mylist");
var item2 = $("#mytable");
$.ajax({
type: "GET",
url: "data.json",
success: function(response) {
$.each(response, function(i, item) {
element.append("<li>" + item.fname + " " + item.lname + "</li>");
item2.append("<tr><td>" + item.lname + "</td>" + "<td>" + item.fname + "</td></tr>");
});
},
error: function() {
alert("error");
}
});
$("#additem").on('click', function() {
var $fname = $("#fname");
var $lname = $("#lname");
var $city = $("#city");
var order = {
fname: $fname.val(),
lname: $lname.val(),
city: $city.val()
};
console.log(order);
$.ajax({
type: "POST",
url: "data.json",
data: order,
succes: function() {
console.log("succes");
},
error: function() {
console.log("no success");
}
});
});
JSFiddle
The problem is you are trying to post to a .json file, like Patrick Evans says in the comments. You need to do the post to a script, in PHP you could do something like this:
$order = $_POST['order'];
// Do something with order...
echo $order; // or echo success message
Of course for this to work you will need PHP to be running on your server (localhost).

How to send and retrieve information/

I have a php file saven on a different domain, and Im using this piece of code to send the username and with that get the info of the user.
Im trying to do something like this, but this is not working is there a way to do it.
var dataString = "username="+username+"";
var url = "";
$.ajax({
type: "POST",
url: url,
data: dataString,
crossDomain: true,
cache: false,
success: $.getJSON(url, function(result)
{
console.log(result);
$.each(result, function(i, field)
{
var id = field.id;
var username = field.username;
var email = field.email;
$('#profile-info').append("ID: " + id + "<br>Username: " + username + "<br>Email: " + email + "<br><br>");
});
})
});
Replace the $.getJSON() function you have for the success calback provided by the jQuery ajax function, and you can pass directly the username through the data parameter as { username : username }, because it's already defined.
Then when you receive successfully your data you can iterate over each result using the jQuery $.each function.
Do you really need to set the cache parameter to false?, just to know.
Also if you want use let instead of var, those variables will be just within the $.each "block".
<script>
var url = '';
$.ajax({
type: "POST",
url: url,
data: { username: username },
crossDomain: true,
cache: false,
success: function(result) {
console.log(result);
$.each(result, function(i, field) {
let id = field.id,
username = field.username,
email = field.email;
$('#profile-info').append("ID: " + id + "<br>Username: " + username + "<br>Email: " + email + "<br><br>");
});
}
});
</script>

wordpress ajax returning zero instead of string message

My ajax call is returning zero even though I wrote die() at the end of my PHP function.
I looked over the other questions here and did not figure it out, please take a look at my code
I make an ajax call using this function:
$('.aramex-pickup').click(function() {
var button = $(this);
var pickupDateDate = $('.pickup_date').val();
var pickupDateHour = $('.pickup_date_hour').val();
var pickupDateMinute = $('.pickup_date_minute').val();
var pickupDate = pickupDateDate + ' ' + pickupDateHour + ':' + pickupDateMinute;
var orderId = button.data('id');
if (pickupDate) {
//show loader img
button.next('.ajax-loader').show();
var data = {
'action': 'aramex_pickup',
'order_id': orderId,
'pickup_date': encodeURIComponent(pickupDate)
};
$.ajax({
url: ajaxurl,
data: data,
type: 'POST',
success: function(msg) {
console.log(msg);
if (msg === 'done') {
location.reload(true);
} else {
var messages = $.parseJSON(msg);
var ul = $("<ul>");
$.each(messages, function(key, value) {
ul.append("<li>" + value + "</li>");
});
$('.pickup_errors').html(ul);
}
}, complete: function() {
//hide loader img
$('.ajax-loader').hide();
}
});
} else {
alert("Add pickup date");
}
return false;
});
in the back-end I wrote this function just to test the ajax is working ok:
public function ajax_pickup_callback() {
echo 'ajax done';
die();
}
I registered the action by:
add_action('wp_ajax_aramex_pickup', array($this, 'ajax_pickup_callback'));
all of this returns 0 instead of "ajax done".
Any help please?
Actually your hook is not get executed. You have to pass the action in the ajax request as you can see here.
jQuery.post(
ajaxurl,
{
'action': 'add_foobar',
'data': 'foobarid'
},
function(response){
alert('The server responded: ' + response);
}
);

How to correctly post data with ajax into div?

Script:
function buttonBuild(id, building, nick)
{
$("#BuildedBox").ajax({
type: "POST",
url: "BlockEditor/build.php",
data: 'block_id=' + id + '&building=' + building + '&nick=' + nick,
cache: false,
success: function(response)
{
alert("Record successfully updated");
$.load("#BuildedBox")
}
});
}
build.php:
include_once("$_SERVER[DOCUMENT_ROOT]/db.php");
$block_id = $_GET['block'];
$building = $_GET['building'];
$nick = $_GET['nick'];
echo"$block_id - $building - $nick";
index.php:
<a href=\"#\" onClick=\"buttonBuild(k152, digger, Name);\" >[BUILD]</a>
<div id="BuildedBox"></div>
seems my script wont work. what i have done wrong?
check this out
function buttonBuild(id, building, nick)
{
$.ajax({
type: "POST",
url: "BlockEditor/build.php",
data: 'block_id=' + id + '&building=' + building + '&nick=' + nick,
cache: false,
success: function(response)
{
alert("Record successfully updated");
/***************/
$("#BuildedBox").html(response);
/***************/
}
});
}
var weightd = $("#weight").val();
var user_id = 43;
$.ajax({
type: "POST",
url:"<?php bloginfo('template_directory')?>/ajax/insert.php",
data: { weight:weightd,user_ids:user_id},
success:function(result){
$("#result1").html(result);
});
<div id="result1">Result div</div>
change $.load("#BuildedBox") to $("#BulderBox").html(response).
When you ask the script for data via ajax, the data provided gets into the "response" variable. As you want to write this data into the div, you must use the ".html" method.
Easier using "load" in this way:
function buttonBuild(id, building, nick)
{
$("#BuildedBox").load("BlockEditor/build.php?block_id=" + id + "&building=" + building + "&nick=" + nick);
}
The "load" method loads data from the server and writes the result html into the element: https://api.jquery.com/load/
EDIT:
As #a-wolff says in the comment, to use POST in load, you should construct like this:
function buttonBuild(id, building, nick)
{
$("#BuildedBox").load("BlockEditor/build.php",{
block_id:id,
building:building,
nick:nick
});
}

How to pass url parameters in jQuery

I am implementing the jQuery Easy UI plugin for checkbox tree. I am having a problem while loading the node data from my action class. The url property does not seem to accept the parameters -
If i give url: '/webapp/fetchData' i'm able to get the data. But if I give
url: '/webapp/fetchData?nodeId='+nodeId
my action class is not able to get the nodeId parameter.
Any solution?
Edit Code ported from comment:
onExpand: function(node) {
alert("inside expand");
var nodeId = node.id;
url: '/webapp/fetchdata?nodeId='+nodeId ;
}
Try this:
Using POST
function DoAction( id, name )
{
$.ajax({
type: "POST",
url: "someurl.php",
data: "id=" + id + "&name=" + name,
success: function(msg){
alert( "Data Saved: " + msg );
}
});
}
Using GET
function DoAction( id, name )
{
$.ajax({
type: "GET",
url: "someurl.php",
data: "id=" + id + "&name=" + name,
success: function(msg){
alert( "Data Saved: " + msg );
}
});
}
Here is what works for me:
Solution 1: from static HTML
javascript: on the caller side:
function onBeforeLoad (node, data)
{
data.Name=name;
}
HTML on the caller side:
<ul id="ScriptTree1" class="easyui-tree" lines="true" data-options="onBeforeLoad:onBeforeLoad, lines:true, processData:false" url="someural.php"/>
Solution 2: from dynamic code:
HTML
<ul id="ScriptTree2" class="easyui-tree" animate="true"></ul>
Javascript function triggered on any specific event:
function filltree ()
{
$('#ScriptTree2').tree
({
dataType:'json',
method:'POST',
lines: true,
processData:false,
onBeforeLoad: function (node,param) { param.Name=name; return true;},
onLoadError: function (dom)
{
if (!String.prototype.trim)
{
String.prototype.trim=function(){return this.replace(/^\s+|\s+$/g, '');};
}
var sResponse = new String (arguments[0].responseText);
alert ('Compl: ' + arguments[1] + ' ' + arguments[2].description + ' ' + arguments[2].name + '\r\nAnswer:\r\n' + sResponse.trim() + '\r\nQuery: \r\n' + decodeURIComponent(arguments.caller.caller.caller[0].data));
return true;
},
url:'someurl.php'
});
}
and callee script:
someurl.php
<?
if ($_POST['Name'] != '') {$Name=$_POST['Name'];} else {$Name='';};
if ($_POST)
{
$kv = array();
foreach ($_POST as $key => $value)
{
$kv[] = "$key=$value";
}
$query_string = join(" | ", $kv);
}
echo '[{"id":100,"text":"params","state":"open","children":[{"id":104,"text":"query_string: '.$query_string.'","state":"open"}]}]';
?>

Categories