After ajax reload, query cannot get id from url - javascript

I create a button with ajax, when I click the button it will make an ajax request which executes a php file. The problem is I need to pass the URL Id into the php page in order to continue the query. When ajax reloads it just refreshes the div only so the system cannot get the ID.
Is there any solution to pass the ID into ajax side.
Here is the javascript
$('.like-btn').on('click',function(){
var postID = $(this).attr("id");
var user_id = $("#userID").val();
var theclass = $(this).attr("class");
var act= '';
var tempScrollTop = $(window).scrollTop();
if($(this).hasClass("like-h"))
{
act = 'unlike';
}
else if($(this).hasClass("unlike-h"))
{
act = 'like';
}
else
{
act = 'like';
}
$.ajax({
type:"POST",
url:"ajax/likeajax.php",
data: {'act':act,'postID':postID,'uid':user_id},
success: function(data){
$("#viewprofile").load("viewviewprofile.php");
$("#puid").val(data);
$(window).scrollTop(tempScrollTop);
}
});
I cannot get the id with
$puid= $_GET['clickuid'];
This is the query
$puid = $_GET['clickuid'];
$query = mysqli_query($con,"SELECT * FROM status WHERE uid=$puid ORDER BY date DESC ");

2 things:
1) You are using POST and trying to access GET (either change your type to GET or change $_GET in php to $_POST)
2) You're not passing the clickuid param

Related

jQuery error in client post response - POST HTTP/1.1" 400

I can't figure out what is wrong with my code and I'm not really good with jQuery.
I'm trying to build HTML form will hold cars data. It's based on this form:
HTML source code is here.
Form data is sent on button click on the end back to program.
I upgraded that form with cascading manufacturer (proizvodjac in code) and car models droplist based on this code. But it's not working.
I keep receiving HTTP 400 which would mean that my POST call from client is malformed.
Here is my jQuery functions:
$(function () {
var carsdata = {"alfaromeo":["mito","156","147","giulietta","159","166","146"],"audi":["a3","a4","a6","a5","80","a1","q3","a8","q5"],"bmw":["320","116","x3","316","318","118","530","x1","520","x5","525","330","120","323","serija 1"],"chevrolet":["spark","lacetti","captiva","aveo","cruze"],"citroen":["c4","c4 grand picasso","c3","c5","c4 picasso","xsara","berlingo","c2","xsara picasso","saxo","ds5","c1"],"fiat":["brava","bravo","panda","grande punto","stilo","punto","punto evo","doblo","500","tipo","uno","coupe"],"ford":["c-max","fiesta","focus","mondeo","fusion","ka","escort"],"honda":["civic","accord","cr-v"],"hyundai":["getz","i10","i20","atos","i30","coupe","elantra","accent","santa fe","ix35","tucson"],"kia":["rio","pro_cee'd","sportage","cee'd","pride","sorento"],"mazda":["3","2","323 f","626","6","cx-5","323","premacy","5"],"mercedes":["a-klasa","c-klasa","e-klasa","b-klasa","124"],"mercedes-benz":["e-klasa","clk-klasa","c-klasa","s-klasa","190","a-klasa","b-klasa","c t-model","ml-klasa","w 124","124"],"nissan":["qashqai","x-trail","note","primera","micra","juke","almera"],"opel":["corsa","astra","zafira","meriva","vectra","insignia","mokka","tigra","combo","astra gtc","kadett"],"peugeot":["308","207","206","306","106","307","208","406","508","407","partner","3008","405"],"renault":["thalia","clio","scenic","grand scenic","kangoo","captur","megane grandtour","megane","laguna","5","megane break","twingo","modus","kadjar","megane classic","espace","megane scenic","megane coupe","megane sedan"],"seat":["toledo","leon","ibiza","altea","cordoba"],"skoda":["fabia","octavia","120","superb","felicia","rapid"],"smart":["fortwo"],"toyota":["corolla","yaris","auris","avensis","rav 4","land cruiser"],"vw":["polo","golf v","golf iv","golf vii","passat","golf vi","jetta","passat variant","caddy","sharan","tiguan","golf variant","golf ii","vento","golfplus","golf iii","bora","touran","touareg","up!"]};
var proizvodjac = $('<select id="proizvodjac"></select>');
var model = $('<select id="model"> </select>');
$.each(carsdata, function(item, key) {
proizvodjac.append('<option >' + item + '</option>');
});
$("#containerProizModel").html(proizvodjac);
$("#proizvodjac").on("change", function(e) {
var item;
var selected = $(this).val();
if (selected === "alfaromeo") {
item = carsdata[selected];
} else {
item = carsdata[selected];
}
$(model).html('');
$.each(item, function(item, key) {
model.append('<option >' + key + '</option>');
});
});
$("#containerProizModel").append(model);
$("button#predict").click(function(e){
e.preventDefault();
/*Get for variabes*/
var kilometraza = $("#kilometraza").val(), godina_proizvodnje = $("#godina_proizvodnje").val();
var snaga_motora = $("#snaga_motora").val(), vrsta_goriva = $("#vrsta_goriva").val();
/*create the JSON object*/
var data = {"kilometraza":kilometraza, "godina_proizvodnje":godina_proizvodnje, "proizvodjac":proizvodjac, "model":model, "snaga_motora":snaga_motora, "vrsta_goriva":vrsta_goriva}
/*send the ajax request*/
$.ajax({
method : "POST",
url : window.location.href + 'api',
data : $('form').serialize(),
success : function(result){
var json_result = JSON.parse(result);
var price = json_result['price'];
swal('Predviđena cijena auta je '+price+' kn', '','success')
},
error : function(){
console.log("error")
}
})
})
})
Comments and explanations are in the code.
On server side:
Server is expecting user_input dictionary which is built from variables returned by POST request. Here is how API method looks:
#app.route('/api',methods=['POST'])
def get_delay():
result=request.form
proizvodjac = result['proizvodjac']
model = result['model']
godina_proizvodnje = result['godina_proizvodnje']
snaga_motora = result['snaga_motora']
vrsta_goriva = result['vrsta_goriva']
kilometraza = result['kilometraza']
user_input = {'proizvodjac':proizvodjac,
'model':model,
'godina_proizvodnje':godina_proizvodnje,
'snaga_motora':snaga_motora,
'vrsta_goriva':vrsta_goriva,
'kilometraza':kilometraza
}
print(user_input)
a = input_to_one_hot(result)
price_pred = gbr.predict([a])[0]
price_pred = round(price_pred, 2)
return json.dumps({'price':price_pred});
Error from Google Chrome Developer Console:
which is pointing to:
EDIT 1:
I don' know how to pass proizvodjac and model to onClick function. See what happens on breakpoint:
XHR on Network tab:
HTML form is being filled with data OK only manufacturer and model are not passed to onClick:
EDIT 2:
Getting closer to solution. I've added :
var proizvodjac = $("#proizvodjac").val()
var model = $("#model").val()
as suggested and now all variables are successfully passed!
But I still get error 400 as final ajax POST call is getting stuck somwhere..
EDIT 3:
changed from
data : $('form').serialize()
to
data = data
AJAX method receives everything ok:
Still it doesn't work.
There are two main issues here:
1) you aren't getting the values from two of your fields correctly. You need to add
var proizvodjac = $("#proizvodjac").val()
var model = $("#model").val()
inside the $("button#predict").click(function(e){ function.
2) You're collecting all these values and putting them into your data variable...but then you aren't doing anything with it. Your AJAX request is configured as follows in respect of what data to send:
data : $('form').serialize()
The serialize() function automatically scoops up all the raw data from fields within your <form> tags. In your scenario, if you want to send a custom set of data (rather than just the as-is contents of the form) as per your data object, then you simply need to change this to
data: data
so it sends the information from that object in the POST request instead.

Why is my ajax request returning an empty object from wordpress?

In my functions.php file I have a function:
function get_news_recipes()
{
global $wpdb;
$interval=$_REQUEST['interval'];
$getPosts = $wpdb->get_results("SELECT ID FROM wp_posts WHERE post_status='publish' AND post_type='post' LIMIT 3 OFFSET ".$interval."");
foreach ($getPosts as $blog)
{
$id=$blog->ID;
$title=get_the_title($id);
$url=get_permalink($id);
$content=get_the_content($id);
$image=wp_get_attachment_url(get_post_thumbnail_id($id));
$postArray[$id]=array(
'title'=>$title,
'content'=>$content,
'url'=>$url,
'image'=>$image
);}
echo wp_send_json($postArray);
die();
}
and in my scripts files I have the ajax setup like this:
function getNewsPosts(interval) {
jQuery.ajax({
url : ajaxurl,
type : 'post',
data : {
action : 'get_news_recipes',
interval:interval,
},
success : function( response ){
//get and store references to modules in slides
var imgs = jQuery('.js-slideImg');
var titles = jQuery('.js-slideTitle');
var contents = jQuery('.js-slideContent');
var links = jQuery('.js-slideURL');
var count = 0;
//interate over each slide and replace html
for(var key in response){
if(response.hasOwnProperty(key)){
jQuery(imgs[count]).css('background-image', 'url('+response[key].image+')');
jQuery(titles[count]).html(response[key].title);
jQuery(contents[count]).html(response[key].content);
jQuery(links[count]).attr('href', response[key].url);
count++;
}
}
}
});
}
Everything works great except the content in response is coming back empty and I can't figure out why. The image url, actual url, and title all come back as expect, however the content is an empty string.
The function get_the_content must be used in the loop otherwise it won't return anything. You should use the following code to the the content of a post.
$post = get_post($id);
$content = $post->post_content;
Modifying your code it would be the following
$id=$blog->ID;
$content=$blog->post_content;

PHP/JS Ajax _POST Array not Posting

there's something strange going on in my ajax code. I'm have some difficulty narrowing it down.
JavaScript:
//Discard Displaying Cards
$(".discard").click(function(){
var gameId = 20;
var cardArray = [];
$( ".card" ).each(function() {
var cardId = $(this).attr('id');
cardArray.push(cardId);
});
$.ajax({
type: 'POST',
url: './system/actions/discard.php',
data: "gameId=" + gameId + "&cardArray=" + cardArray,
success: function(data) {
console.log(cardArray);
console.log("Success.");
console.log(data);
}
});
});
The javascript posts to a file discard.php where it is given two parameters: gameId and cardArray. gameId is static right now, but cardArray is made up of the DOM ids of each of the ".card" elements loaded on the page. Each DOM id reflects the card_id in my database.
discard.php
//Classes
include $_SERVER["DOCUMENT_ROOT"] . '/system/classes/cards.php';
header("Content-Type: text/html");
$gameId = empty($_GET['gameId']) ? '' : $_GET['gameId'];
$numbers = empty($_GET['cardArray']) ? '' : $_GET['cardArray'];
$regex = preg_replace('/[^,;a-zA-Z0-9_-]|[,;]$/s', '', $numbers);
$cardArray = explode(",", $regex);
foreach ($cardArray as $cardId) {
discardCards($cardId, $gameId);
};
The discard.php is supposed to read the $_GET headers from the ajax request. But for some reason, it fails. The funny thing is, if I call the page directly with manual GET headers, e.g I browse to:
domain.com/system/actions/discard.php?gameId=20&cardArray=["1","3"]
OR even
domain.com/system/actions/discard.php?gameId=20&cardArray=1,3
The script works fine!
I thought it may have been something with the format ajax is posting in, hence the regex, but alas, it did not work. Because I'm not even sure how to display or view the requested ajax data URL on the page it called on, I'm finding it particularly difficult to debug.
Any suggestions? Thanks in advance.
You are using:
type: 'POST',
But you are receiving it as $_GET, change it to $_POST:
$gameId = empty($_POST['gameId']) ? '' : $_POST['gameId'];
$numbers = empty($_POST['cardArray']) ? '' : $_POST['cardArray'];
Or change the AJAX function to:
type: 'GET',
And also, the data is supposed to be a string. So use serialize():
$(form_id).serialize();
Where form_id is the id of the form.

how to refresh dynamically generated divs using ajax?

I am generating dynamic divs and need to refresh them every 10 seconds.
Earlier I used meta refresh but didn't like the flickering of page.
I have tried to insert the ajax code but got failed.
below is my code without ajax,please tell me how and where to insert the ajax refresh code.
$(document).ready(function (){
var n = 9;
for(var i=0; i<n; i++){
var div = document.createElement('div');
div.className = "d5";
div.id=i+1;
// alert(div.id);
document.getElementById('container').appendChild(div);
$.ajax({
async : false,
url : 'myapi.php', //the script to call to get data
data : "", //you can insert url argumnets here to pass to api.php for example "id=5&parent=6"
dataType : 'json', //data format
success : function(data){ //on recieve of reply
var Name = data[2];
var subdomain = data[15];
var uniqueid = data[1];
var shop_photo = data[3];
var offer = data[19]; //get id
//var vname = data[1]; //get name
//$('#'+div.id).html("<a href='http://www."+subdomain+".shoppinonline.com'>"+Name+"</a>");
//$('#'+div.id).html("<img class='shopperspic' src='b2b/shop_image/"+uniqueid+"/"+shop_photo+"' alt='' /><a href='http://www."+subdomain+".shoppinonline.com'>"+Name+"</a><br>Special Offer<br><p>"+offer+"</p>");
if(offer == ""){
$('#'+div.id).html("<div class='div1'><img class='shopperspic' src='b2b/shop_image/"+uniqueid+"/"+shop_photo+"' alt='' /></div><div class='div2'><a href='http://www."+subdomain+".shoppinonline.com'>"+Name+"</a></div></div>");
}else{
$('#'+div.id).html("<div class='div1'><img class='shopperspic' src='b2b/shop_image/"+uniqueid+"/"+shop_photo+"' alt='' /></div><div class='div2'><a href='http://www."+subdomain+".shoppinonline.com'>"+Name+"</a></div><div class='div3'>Special Offer<br class='br_special'>"+offer+"</div></div>");
}
}
});
}
});
First, enclose your existing code(loop and the ajax call) in a function. You can then create a setTimeOut loop using recursion and get your function called every 10 seconds .
$(document).ready(function(){
timeout();
function timeout() {
setTimeout(function () {
//Call the function that makes the ajax request
//This code will re-execute after every 10 seconds
timeout();
}, 10000);
}
});
Also, doing async: false, you are actually abusing the very nature of ajax calls. It will block your script until the request has been fulfilled.
Cheers!
Set A timer Of Ten Second And Call Ajax Method Inside That I think This Will Solve Your Problem

How to use HTML data from ajax call

i have a load more button on some content that is pulled from a database via ajax.
The ajax call looks like so:
// JavaScript Document
// load more builds function
$(document).ready(function(){
var pageIndex = 1;
$('#loadmorebuilds-div').click(function() {
$.ajax({
url: 'includes/loadmorebuilds.php?type=' + type + '&pageIndex=' + pageIndex,
success: function(html) {
$("#buildcontainer").append(html).waterfall('reflow');
$("#loadmorebuilds-div").stop().fadeOut();
pageIndex++;
var rowCount = MAKE THIS THE VALUE THAT IS APPENDED;
$('.testcount').html(rowCount);
if (rowCount < 18) {
$('#loadmorebuilds-div').remove();
$('.countvar').detach();
} else {
$('.countvar').detach();
}
}
});
});
});
In the appended items, is a div that contains a value of the row count for the database query that has been carried out via the above ajax call.
Normally, i would put this value into a JSON return and simply do e.g.:
rowCount = response.rowCount
However i am not using a JSON datatype but HTML.
How can i get this value from the appended div in the data and use it to set a var?
Thanks!
Use either:
val = $("#thatDiv").text();
or
val = $("#thatDiv").attr("value");
The latter of which, is if you put the value in a pseudo attribute...

Categories

Resources