How to compare, then update in AJAX if necessary - javascript

I have a list containing news articles in the backend of a site which is then displayed on a homepage. I'd like the homepage to always display the most recent news.
I've never used AJAX before but in pseudo it would need to do the following:
call the homepage using an AJAX-get
Compare the article div with the same div from the AJAX-get.
If the AJAX-get has different content inside the div, display that
Can I do this with Jquery load, or do I need to go into AJAX for this functionality. and if so, could anyone give me a hand with the AJAX itself
trying to use AJAX, i have started using the following code, to no avail
$.ajax({
url: ctx.HttpRoot,
data: { "id": $("newsSliderWrapper").attr("id") },
success: function (data) {
data = $(data).find('div#newsSliderWrapper')
alert(data)
},
error: function () {
// your error logic
alert("AJAX failed");
}
})

AJAX in your case will do the following:
Ajax call will send the recent article ID to the server.
The server will compare the article ID. If the article ID is different, then the server will return the new article content. If the id is same, return different status message.
Ajax call will simply render the content
So
$.ajax({
url : "backendurl",
data : {"id" : $("recentarticleDivId").attr("id")},
// id must be the article ID which you need to match
success : function(data) {
$("#articleDivId").html(data);
},
error : function() {
// your error logic
}
})

$.ajax({
url: "homepage.php",
type: "GET",
data: { id : article_id },
success:function(data){
console.log(data);
// your logic
},
error:function(){
}
});

Related

JSON Data cannot be stored in variable

Im trying to load the content of a JSON File into an variable.
Before, the variable looked something like this:
var Data = {
teams : [
["Team 1", "Team 2"],
["Team 3", "Team 4"]
],
results : [
[[1,2], [3,4]],
[[4,6], [2,1]]
]}
Now I have a JSON File looking something like this:
{"teams":[["Team 1","Team 2"],["Team 3","Team 4"],"results":[[[[1,2],[3,4]],[[4,6],[2,1]]]}
Now I want that the the content of the JSON File is stored in the Data Variable before. I tried it with Ajax which looks like this:
$.ajax({
type: "GET",
dataType : 'json',
async: true,
url: 'data.json',
success: function(data) {
console.log(data)
var Data = data
},
});
Console.log works perfect, but the Data is not saved in the variable and I'm getting the error: Uncaught ReferenceError: Data is not defined.
I also tried it with var Data = JSON.parse(data), but this doesn't seem to work either.
And now I'm stuck without any clue.
Thanks for help in advance.
I'm not sure what your code looks like after the ajax call, but I'm guessing the the code where you are using Data is after the ajax call. ajax is asynchrounous. That means that your code doesn't wait for it to finish before moving on. Any code that needs to wait until after it's done fetching the data, you can put in the .success function. Also, it's worth noting that success only gets called when the ajax request is successful. If you want to handle errors, you can use .error Something like this should work:
$.ajax({
type: "GET",
dataType : 'json',
async: true,
url: 'data.json',
success: function(data) {
console.log(data)
var Data = data;
// Anything that needs to use Data would go inside here
},
error: function(err) {
// handle errors
console.error(err);
}
});
// Any code here will not wait until `Data` is defined
// console.log(Data) // error

Ajax and PHP, post request not working

So I am trying to post some some data from one PHP file to another PHP file using jquery/ajax. The following code shows a function which takes takes data from a specific div that is clicked on, and I attempt to make an ajax post request to the PHP file I want to send to.
$(function (){
$(".commit").on('click',function(){
const sha_id = $(this).data("sha");
const sha_obj = JSON.stringify({"sha": sha_id});
$.ajax({
url:'commitInfo.php',
type:'POST',
data: sha_obj,
dataType: 'application/json',
success:function(response){
console.log(response);
window.location.replace("commitInfo");
},
error: function (resp, xhr, ajaxOptions, thrownError) {
console.log(resp);
}
});
});
});
Then on inside the other php file 'commitInfo.php' I attempt to grab/print the data using the following code:
$sha_data = $_POST['sha'];
echo $sha_data;
print_r($_POST);
However, nothing works. I do not get a printout, and the $_POST array is empty. Could it be because I am changing the page view to the commitInfo.php page on click and it is going to the page before the data is being posted? (some weird aync issue?). Or something else? I have tried multiple variations of everything yet nothing truly works. I have tried using 'method' instead of 'type', I have tried sending dataType 'text' instead of 'json'. I really don't know what the issue is.
Also I am running my apache server on my local mac with 'sudo apachectl start' and running it in the browser as 'http://localhost/kanopy/kanopy.php' && 'http://localhost/kanopy/commitInfo.php'.
Also, when I send it as dataType 'text' the success function runs, but I recieve NO data. When I send it as dataType 'json' it errors. Have no idea why.
If anyone can help, it would be greaat!
You don't need to JSON.stringify, you need to pass data as a JSON object:
$(function() {
$(".commit").on('click', function() {
const sha_id = $(this).data("sha");
const sha_obj = {
"sha": sha_id
};
$.ajax({
url: 'commitInfo.php',
type: 'POST',
data: sha_obj,
dataType: 'json',
success: function(response) {
console.log(response);
},
error: function(resp, xhr, ajaxOptions, thrownError) {
console.log(resp);
}
});
});
});
And on commitInfo.php, you have to echo string on json format
=====================================
If you want to redirect to commitInfo.php you can just:
$(".commit").on('click',function(){
const sha_id = $(this).data("sha");
window.location.replace("commitInfo.php?sha=" + sha_id );
});

MVC 5 generate form data with AJAX

I need a way to generate a new unique id for a user when a person focuses out of a textbox. I am using MVC 5 for this application. Here is my controller, everything in the controller has been unit tested and it does return the string value that I need.
Controller. I was able to visit that URL, and I did download a JSON file with the correct data.
public ActionResult GetNewId()
{
string newId = utils.newEmployeeId();
return Json(new {eId = newId}, JsonRequestBehavior.AllowGet);
}
Javascript, JQuery call to that controller. I do not know how to properly reference the ActionResult. I keep getting undefined errors on eId.
$(function () {
$('#employeeId').focusout(function () {
if($("#employeeId").val() === "NP")
$.ajax({
type: 'GET',
url: '#Html.ActionLink("GetNewId", "Employees")',
data: { 'eId': eId },
dataType: 'json',
success: function (response) {
$("#employeeId").val(eId);
},
error: function (response) {
alert(response);
}
});
});
});
The problem is with yout ajax request:
1.you need to change the url in the reuqest but it like this
{{yourcontroller}/GetNewId}
2.remove the "data: { 'eId': eId }" you dont need it, youre not posting anything to the server.
change your $("#employeeId").val(eId); to
$("#employeeId").val(response.eId);
this will 100% work

Jquery Ajax Server Polling; Polling the server based on an earlier ajax response

What I am trying to do:
1. Initially gives an ajax request to the server based on some inputs
2. The server returns a job id generated by RQ (Python-rq)
3. Based on the job id ajax request made to a url constructed with the jobid regularly till a valid response is obtained
What I have:
$.ajax({
type: "POST",
url: "/start",
data:{crop: valueCrop, state: valueState, variablemeasure: valueVariable, unit:unitMeasure, from:yearFrom, to:yearTo},
success: function(results) {
console.log(results);
var jobId='';
jobId = results;
function ajax_request() {
$.ajax({
type: "GET",
url: "/results/" + jobId,
dataType: "json",
success:function(xhr_data) {
if (xhr_data == {"status":"pending","data":[]}){
console.log("Waiting for response");
setTimeout(function() { ajax_request(); }, 2000);
} else {
console.log(xhr_data);
}
},
error:function(error) {
console.log(error)
}
});
}
},
error: function(error) {
console.log(error)
}
})
Is this even possible? I am not getting any output at all on the console although the rq says the job is finished. I think it is not entering that if loop. When I visit the "/results/jobId" url I am able to see the result.
Please help.
I see a few bugs in this code. First of all, you have defined the function ajax_request(). But you are not calling it. You can call it at the end of its definition.
Secondly, this code is problematic:
if (xhr_data == {"status":"pending","data":[]})
The object notation creates another object which is definitely not equal to xhr_data.
You can do:
if (xhr_data.status === "pending")

JQuery Ajax not sending data to PHP

myscript.js below is outputing:
[{"orcamento":"10","atual":"20","desvio":"","data":"2015-01-01","nome_conta":"BBB","nome_categoria":"abc","nome_entidade":"def"}]
myscript.js:
if (addList.length) {
$.ajax($.extend({}, ajaxObj, {
data: { "addList": JSON.stringify(addList) },
success: function (rows) {
$grid.pqGrid("commit", { type: 'add', rows: rows });
},
complete: function () {
$grid.pqGrid("hideLoading");
$grid.pqGrid("rollback", { type: 'add' });
$('#consola').text(JSON.stringify(addList));
}
}));
}
The JSON data above has to be sent to my script.php below:
if( isset($_POST["addList"]))
{
$addList = json_decode($_POST["addList"], true);
var_dump ($addList);
echo "test";
exit();
}
Although the data is correct and myscript.php is being called it isn't returning anything. I get:
NULLtest
I tried using GET, instead of POST but the result is the same, what is wrong with the code above?
EDIT:
Here's the ajaxObj used in the ajax request:
var ajaxObj = {
dataType: "json",
url:"../myscript.php",
type: "POST",
async: true,
beforeSend: function (jqXHR, settings) {
$grid.pqGrid("showLoading");
}
};
From the PHP Docs on json_decode:
NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit.
So it is most likely that there is some error in your JSON data that is preventing json_decode from parsing it correctly, I've ran that snippet through jsonlint and it does say that it's valid JSON, but it's worth checking a larger sample of the data you send to the server for inconsistencies.
Other than that, is there any reason that you are calling JSON.stringify on the data object prior to sending to the server? I would try just sending the object itself as the data parameter of your AJAX call like so:
$.ajax($.extend({}, ajaxObj, {
data: { "addList": addList },
success: function (rows) {
$grid.pqGrid("commit", { type: 'add', rows: rows });
},
complete: function () {
$grid.pqGrid("hideLoading");
$grid.pqGrid("rollback", { type: 'add' });
$('#consola').text(JSON.stringify(addList));
}
}));
And see if that helps:
EDIT
I should have noticed in my original answer, you will not need to call json_decode on your posted data, jQuery encodes the data as post parameters correctly for you; It should be accessible within your PHP script as an associative array, try replacing your current var_dump statement in your PHP var_dump($_POST['addList'][0]['orcamento']); and you should be good to go.
First of all, be sure you are posting to a php file, use firebug or similar tools to track your script..
I don't see the part you defined the target PHP file on your javascript file..
A regular javascript code can look like this :
jQuery.ajax({
type : "post",
dataType : "json",
url : 'target.php',
data : {foo:bar },
success: function(response) {
// do something with response...
}
});
If you see that you are posting to the right php file the right parameters on firebug, try to use $_REQUEST if $_POST not working..
Firebug will show you the response of PHP file.. so do a print_r($_REQUEST['addList']) to see what is going on...

Categories