I am working with a jQuery-function to trigger an ajax request on click. However, I don't get a result though the script should send a value via post-method. It looks like the PHP-script doesn't receive the value, but probably the problem is elsewhere.
Maybe somebody can tell me where the problem is.
doClick = function (sender){
var jid = sender.id;
if ($(window).width() < 768) {
$('.jwin').addClass('order-md-1').removeClass('order-md-2').removeClass('d-none');
$('.jobs').addClass('order-md-2').removeClass('order-md-1').removeClass('d-block').addClass('d-none');
var ink = document.getElementById('ajax').value;
$.ajax({
url:"get_job.php",
method:"POST",
data:{jid:jid},
cache:false,
dataType: "json",
contentType: "application/json; charset=utf-8",
success:function(data)
{
//console.log(data.success);
if(data.success == TRUE)
{
//$('#ajax').text(data.nurl);
$('#title').text(data.title);
$('#crp').text(data.compnme);
$('#descript').html(data.jtxt);
$('#jadoci').text(data.city);
$('#jadost').text(data.state);
$('#connx1').css("display", "inline");
$('#connx2').css("display", "inline");
$('#applylink').css("display","block");
$('#applylink').attr('href',"links?jid="+jid);
if(data.url==''){
$('#applylink').css("display","none");
}
}else{
// Fade in
alert(data.success);
}
}
});
$('#returnmobile').append("<a href=''>"+jid+"</a>");
}
else {
$.ajax({
url:"get_job.php",
method:"POST",
data:{jid:jid},
cache:false,
dataType: "json",
contentType: "application/json; charset=utf-8",
success:function(data)
{
//console.log(data.success);
if(data.success == TRUE)
{
//$('#ajax').text(data.nurl);
$('#title').text(data.title);
$('#descript').html(data.jtxt);
if(data.company==0){
$('#crp').text("Agent");
}
else{
$('#crp').text(data.compnme);
$('#crp').attr('href','company?id='+data.company)
}
$('#jadoci').text(data.city);
$('#jadost').text(data.state);
$('#connx1').css("display", "inline");
$('#connx2').css("display", "inline");
$('#applylink').css("display","block");
$('#applylink').attr('href',"links?jid="+jid);
if(data.url==''){
$('#applylink').css("display","none");
}
}else{
// Fade in
alert(data.success);
}
}
});
//alert('More than 960');
}
};
And the PHP-code:
require "config.php";
$jid = $_POST["jid"];
$ipa = $_SERVER['REMOTE_ADDR'];
$query = $con->query("SELECT jla.title AS title, jla.summary AS jtxt, jla.city AS city, jla.state AS state, jla.company AS corp, c.name AS company, jla.url AS url, jla.id AS coid FROM jobs jla LEFT JOIN companies c ON c.id = jla.company WHERE jla.id = $jid");
if($query->num_rows > 0){
while($row = $query->fetch_assoc()){
$output = array('success'=>TRUE,
'nurl'=>("<b>Does</b> it work? Yes!"),
'company'=>$row['corp'],
'compnme'=>$row['company'],
'title'=>$row['title'],
'city'=>$row['city'],
'state'=>$row['state'],
'coid'=>$row['coid'],
'url'=>$row['url'],
'jtxt'=>$row['jtxt']);
$quip0 = $con->query("SELECT * FROM clicks WHERE ip = '$ipa' AND job_id = '$jid'");
if($quip0->num_rows < 1){
$quip1 = "INSERT INTO clicks (ip, job_id) VALUES ('$ipa','$jid')";
if ( $con->query($quip1) === TRUE) {
echo json_encode($output,JSON_FORCE_OBJECT);
}
}
else {
echo json_encode($output,JSON_FORCE_OBJECT);
}
}
}
Again: the result I receive seems to be empty. Even in the inspect-mode in Chrome I don't see values that I'd expect, making me suspicious that the $jid value wouldn't be delivered correctly. Btw: sender.id works so far. I used to test this.
You aren't sending json or expecting json at server so remove:
contentType: "application/json; charset=utf-8",
There might be several issues. One common problem is when the request is done from a different domain the server does not serve the request. Use header('Access-control-allow-origin: *') at the start of the file or the function
Use CORS carefully
Related
How is it possible for me to get my Ajax to expect my array within my success. Currently I presume I use a flat object and this needs to grab all the data passed back to the client side so I can update my notifications.
I presume everything else is correct!
{"num":1,"670":{"notification_id":"670","notification_content":"
Lucy Botham posted a status on your
wall","notification_throughurl":"singlepoststreamitem.php?
streamitem_id=545","notification_triggeredby"
"85","notification_status":"1"},"671":
{"notification_id":"671","notification_content":"Lucy Botham
posted a status on your
wall","notification_throughurl":"singlepoststreamitem.php?streamitem_id=546"
,"notification_triggeredby":"85","notification_status":"1"}}
SERVER SIDE
while($row = mysqli_fetch_assoc($com)){
$id = $row['notification_id'];
$num = mysqli_num_rows($com);
if($num){
$json['num'] = 1;
}else{
$json['num'] = 0;
}
$json[$id]['notification_id'] = $row['notification_id'];
$json[$id]['notification_content'] = $row['notification_content'];
$json[$id]['notification_throughurl'] = $row['notification_throughurl'];
$json[$id]['notification_triggeredby'] = $row['notification_triggeredby'];
$json[$id]['notification_status'] = $row['notification_status'];
}
echo json_encode($json);
CLIENT
function loadIt() {
$.ajax({
type: "GET",
url: "viewajax.php?
notification_id="+notification_id+"
¬ification_targetuser="+notification_targetuser+
"¬ification_triggeredby="+notification_triggeredby,
dataType:"json",
success: function(data){
//do something
)
use json.parse()
success: function(data){
var a = JSON.parse(data);
//loop var a to get your data
}
See this link, you might get some idea.
hey i have a problem submitting my data via jquery and back:
$.ajax({
url: "checkAvailability.php",
type: 'POST',
data : {data:JSON.stringify(data)},
success: function(data) {
if (data.result == 0) {
alert("0")
}
if(data.result == 1) {
alert("1")
}
}
});
so,
ONE of those if-conditions must be true, because of:
checkAvailability.php:
if(isset($_POST['data'])) {
define('SECURE', true);
include "storescripts/connect_to_mysql.php";
require 'AvailabilityChecker.php';
$config = array(etc..);
$availabilityChecker = new AvailabilityChecker($config);
$data = $_POST['data'];
$data = json_decode($data,true);
preg_match( '/(\d+(\.\d+)?)/', $data['x'] , $m);
$x = $m[0];
if($availabilityChecker->check_availability($x)) {
echo json_encode(array("error" => "is ok", "result"=>1));
} else {
echo json_encode(array("error" => "not ok", "result"=>0));
}
}
data.result have to be 1 OR 0.
anybody can tell me why there is no alert-message? greetings!
UPDATE:
$.ajax({
url: "checkAvailability.php",
type: 'POST',
data : {data:JSON.stringify(data)},
success: function(data) {
if (data.result == 0) {
alert("0")
} else { alert("fail-1") }
if(data.result == 1) {
alert("1")
} else { alert("fail-2") }
}
});
now i get first the fail-1 alert and than the fail-2 alert, so both if-conditions are false, why?
You need to specify the dataType, otherwise jquery will instead try to guess what you are trying to do. In this case it is incorrectly guessing text/html rather than application/json.
$.ajax({
url: "checkAvailability.php",
type: 'POST',
dataType: 'json',
data : {data:JSON.stringify(data)},
success: function(data) {
if (data.result == 0) {
alert("0")
} else { alert("fail-1") }
if(data.result == 1) {
alert("1")
} else { alert("fail-2") }
}
});
You should also properly set the content-type header in php, before you echo the json.
header('Content-type: application/json');
You can get away with doing either-or, but i'd suggest doing both.
a solution can be
success: function(d) {
data = jQuery.parseJSON(d);
if (data.result == 0) {
alert("0")
}
if(data.result == 1) {
alert("1")
}
}
this becouse $.ajax will no decode the result text from the page for you.
what the php code is doin in fact is to print a json string to the stream.
Note that the the output passed to success can be any sort of text (also xml code on simply text)
You need to set the correct content type header in your php file:
header('Content-Type: application/json');
//snip
echo json_encode(array("error" => "is ok", "result"=>1));
Here is my HTML
<input x-webkit-speech id="mike" name="string" style="position: relative;" disabled lang="ru" />
Then when the field is changes,
This function executes
$(document).ready(function(){
$('#mike').bind('webkitspeechchange',function()
{
a= $(this).val();
recognizeAjax(a);
}) ;
});
function recognizeAjax(string) {
var postData ="string="+string;
$.ajax({
type: "POST",
dataType: "json",
data: postData,
beforeSend: function(x) {
if(x && x.overrideMimeType) {
x.overrideMimeType("application/json;charset=UTF-8");
}
},
url: 'restURL.php',
success: function(data) {
// 'data' is a JSON object which we can access directly.
// Evaluate the data.success member and do something appropriate...
if (data.success == true){
alert(data.message);
}
else{
alert(data.message+'hy');
}
}
});
And here is my PHP (please don't say anything about the way i connect to DB it doesn't metter right now)
<?php header('Content-type: application/json; charset=utf-8');
error_reporting(E_ALL);
ini_set('display_errors', true);
// Here's the argument from the client.
$string = $_POST['www'];
$quest=1;
$con=mysql_connect("localhost", "******", "*********") or die(mysql_error());
mysql_select_db("vocabulary", $con) or die(mysql_error());
mysql_set_charset('utf8', $con);
$sql="SELECT * FROM `text` WHERE event_name = 'taxi' AND quest_id = '".$quest."'";
$result = mysql_query($sql);
mysql_close($con);
while($row = mysql_fetch_array($result))
{
if ($string == htmlspecialchars($row['phrase']))
{
$data = array('success'=> true,'message'=>$row['phrase']);
// JSON encode and send back to the server
header("Content-Type: application/json", true);
echo json_encode($data);
exit;
break;
} else {
// Set up associative array
$data = array('success'=> false,'message'=>'aint no sunshine');
header("Content-Type: application/json", true);
echo json_encode($data);
exit;
break;
}
}
When i change the dataType to "text" in the javasript function - i receive an alert with 'undifiend'
But when chenge it to 'json'.. i receive nothing (chrome debuger see nothing)
I set up all encodings to this article http://kunststube.net/frontback/
And i checked it with simple POST requests - it works perfect.
The problem with json.
Any suggestions?
Thanks
Just remove the datatype="json" bit and change the data bit to data: { "string": string }
After that try a print_r(json_decode($_POST['string']));. I'm quite sure that will get you your data.
And indeed remove your beforeSend callback.
I think the prob is the code var postData ="string="+string;
jQuery expects this to be a proper JSON Object.
Next: $string = $_POST['www']; takes a parameter named "www" from your post request, but the name above is "string" (at least).
Try either (!) this:
var getData ="www="+string;
$.ajax({
type: "POST",
dataType: "json",
data: null,
beforeSend: function(x) {
if(x && x.overrideMimeType) {
x.overrideMimeType("application/json;charset=UTF-8");
}
},
url: 'restURL.php?' + getData,
and server:
$string = $_GET['www'];
or this (php)
$string = $_POST['string'];
$stringData = json_decode($string);
// catch any errors ....
$quest=$stringData[....whatever index that is...];
I'm trying to get my ajax to request information from the server and also keep it alive for at least 1 minuite before having a break and restarting and getting and passing a new streamitem_id if their were one inserted since the last call.
Currently it runs so fast and only once and I don't understand why.
AJAX
<script type="text/javascript" charset="utf-8">
function wait() {
var streamitem_id =<? echo $streamitem_catch['streamitem_id']; ?>;
$.ajax({
type: "POST",
url: "testingajaxfeed.php?streamitem_id=" + streamitem_id,
async: true,
cache: false,,
dataType: "json",
data: {streamitem_id: streamitem_id},
success: function (response) {
setTimeout("wait()",1000);
$("#homestatusid").prepend("MY INSERTED RESPONSE");
},
});
}
$(document).ready(function(){
wait();
});
</script>
PHP
if (isset($_POST['streamitem_id'])) {
$lastID = (int)$_POST['streamitem_id'];
if(empty($lastID)) {
die('timeout');
}
else {
$following_string = $_SESSION['id'];
$result="SELECT d.*, c.*, u.*
FROM streamdata AS d
JOIN streamdata_comments AS c ON d.streamitem_id = c.comment_streamitem
JOIN users AS u ON u.id = c.comment_poster
WHERE d.streamitem_id > '$lastID'
AND c.comment_poster = '$following_string'
AND (d.streamitem_creator = '$following_string')
OR d.streamitem_creator IN $friendlist
AND d.streamitem_type_id NOT IN ('3')
ORDER BY '$lastID' DESC LIMIT 1";
$result = mysqli_query($mysqli, $result) or die(mysqli_error($mysqli));
while ($resultArr = mysqli_fetch_array($result)) {
$json = array();
$json['streamitem_id'] = $resultArr['streamitem_id'];
$json['streamitem_content'] = $resultArr['streamitem_content'];
$json['streamitem_timestamp'] = Agotime($resultArr['streamitem_timestamp']);
$json['comment_id'] = $resultArr['comment_id'];
$json['comment_content'] = $resultArr['comment_content'];
$json['comment_poster'] = $resultArr['comment_poster'];
$json['comment_datetime'] = Agotime($resultArr['comment_datetime']);
$json['comment_streamitem'] = $resultArr['comment_streamitem'];
$json['username'] = $resultArr['username'];
$json['id'] = $resultArr['id'];
$json['first'] = $resultArr['first'];
$json['middle'] = $resultArr['middle'];
$json['last'] = $resultArr['last'];
echo json_encode($json);
}}}
setTimeout does not work like you expect. An ajax-request can't be "kept alive" like you want. The request is sent, the PHP-script returns the content and the ajax-script get's the result. All this happens within ~1-2 seconds.
If this is used for some sort of stream (as it looks like), you would have to make the function repeat itself again and again over a small interval.
I've changed your code like this:
<script type="text/javascript" charset="utf-8">
function wait() {
var streamitem_id =<? echo $streamitem_catch['streamitem_id']; ?>;
$.ajax({
type: "POST",
url: "testingajaxfeed.php?streamitem_id=" + streamitem_id,
async: true,
cache: false,
dataType: "json",
data: {streamitem_id: streamitem_id},
success: function (response) {
$("#homestatusid").prepend("MY INSERTED RESPONSE");
},
});
}
$(document).ready(function(){
setInterval(wait,10000);
});
</script>
The ajax-script will fire every 10 seconds. You can edit the speed yourself, but keep in mind that too many requests in a short timeperiod can make your server crash/go slow.
In your PHP script, you'll need to use the sleep function in order to keep your connection alive.
Something like:
function callScript(callback) {
$.post('myscript.php',{data:data},function(data) {
if (data == -1) {
return callScript(callback);
}
return callback(data);
}
}
myscript.php
$interval = 50;
$iters = floor(1000 / $interval);
while($conditional === false) {
if (--$iters < 1) { die(-1); }
sleep($interval);
}
echo $json;
While this isn't exactly what you need, it can easily be adapted to what you need. I've done this with other stuff, while costly, you can use a sql statements to wait for entries to be added etc.
I'm just trying to spit the elements of an array into seperate input fields on a form via jquery's AJAX.
Heres my javascript code:
$('#based').change(function() {
if ($(this).val().length > 0)
{
$.ajax({
type: "POST",
url: "ajax.php",
data: "id="+$(this).val(),
success: function(data){
if (data != 'error')
{
$('#keyword').val(data[2]);
$('#keyword_slug').val(data[3]);
}
}
});
}
});
Heres my PHP code for 'ajax.php':
$sql = mysql_query("select * from `keywords` where `id`='".mysql_real_escape_string($_POST['id'])."'");
if (mysql_num_rows($sql) == 0)
{
echo 'error';
}
else
{
while ($row = mysql_fetch_assoc($sql))
{
foreach ($row as $k => $v)
$data[] = $v;
}
echo json_encode($data);
}
Its not working. What do I do here? I've looked into serializeArray but can't get anything to work properly.
I think you need dataType: 'json' if you are expecting JSON back.
Otherwise jQuery has to guess, and if you are not sending the Content Type application/json, it may guess wrong.