My JavaScript always returns an error, even if PHP did what it should.
No matter if I write dataType: "JSON" or "JSONP" or delete it completely.
When I remove echo json_encode(... it works as it should. I see the alert for success.
But I want to make two or three success messages appear in-line in html.
Here is my JS code:
jQuery(document).ready(function($){
$('#przypinanie').click(function() {
var data_cat = $('select#cat').val();
var data_post_id = $('input#przypinanie-post-id').val() ;
var przypinanie = $('input#przypinanie').val();
$.ajax({
url: ajaxurl,
data: {
cat_id: data_cat,
post_id: data_post_id,
przypinanie_usuwanie: przypinanie,
action: "przypinanie_php"
},
success: function(data) {
alert(data);
},
error: function(data) {
alert(data);
},
});
});
My PHP code:
if ( $przypinanie == "PRZYPNIJ" ) {
$validate = $wpdb->get_var("SELECT przypieta_cat_id FROM polecane_przypinane WHERE przypiety_post_id = '$post_id'");
if ( isset($validate) ){
$msg = 'Wpis jest już przypięty do kategorii '. $validate ;
}else{
$wpdb->insert( 'polecane_przypinane',
array(
'przypiety_post_id' => $post_id,
'przypieta_cat_id' => $cat_id,
)
);
$msg = 'Wpis został przypięty do kategorii '. $validate ;
}
$responce = $msg;
}
header('Content-type: application/json');
echo json_encode($responce);
OK. Thank You for answers.
I resigned from JSON and I just did echo $responce; at the end of function.
Pleased to solwed my first question here.
Related
I wrote the following code snippet for Ajax connections, but unfortunately the return value is not displayed in the output, but it does not give a special warning to understand the meaning. Please help.
js
$("#search").on('keyup', function(){var value = $(this).val();
$.ajax('feed.php',{
type: 'POST',
dataType: 'json',
data: {
keyword: value
},
success: function(data){
$("#pre").html(data);
}
});
});
feed.php
<?php
require_once('main.php');
$db = Db::getInstance();
$keyword = $_POST['keyword'];
$records = $db->query("SELECT * FROM dic_word WHERE word LIKE '%$keyword%'");
$out['html']= '';
foreach($records as $record){
$out['html'] .= $record['word'] . '<br>';
}
echo json_encode($out);
?>
js:
jQuery('#search').on('keyup', () => {
jQuery.ajax({
url: 'feed.php',
type: 'POST',
data: { keyword: jQuery(this).val() },
success: response => {
jQuery('#pre').html(response);
}
});
});
feed.php
<?php
require_once('main.php');
$database = Db::getInstance();
$keyword = $_POST['keyword'];
$records = $database->query("SELECT * FROM dic_word WHERE word LIKE '%$keyword%'");
$output = '';
foreach($records as $record){
$output .= $record['word'] . '<br />';
}
echo($output);
?>
PS: You don't need to use json output absolutly. But if there is coercion to using json output, the problem is 2 following items:
You don't set the output "Content-Type" to json: header('Content-Type: application/json');
You shouldn't pass the json object to html method in jQuery and should parsing it at first with JSON.parse(response) class, then with foreach, for or anything else process it
I want to call php file from javascript, and this php file will update id=1
like this way:
javascript:
if(lastTemp >= document.getElementById("TempSet").value){
var jsonData2 =$.ajax({
url: "setpp.php",
dataType: "json",
async: false
}).responseText;
var obj2 = JSON.parse(jsonData2);
console.log(obj2);
}
else {
}
php file:
<?php
$DATABASE_HOST = 'localhost';
$DATABASE_USER = 'use';
$DATABASE_PASS = 'pass';
$DATABASE_NAME = 'database';
// Try and connect using the info above.
$db = mysqli_connect($DATABASE_HOST, $DATABASE_USER, $DATABASE_PASS,
$DATABASE_NAME);
if (!$db){
die("Connection Failed: ". mysqli_connect_error());
}
$db_update = "UPDATE setpoint_control SET status='ON' WHERE id=1";
$result = mysqli_query($db, $db_update);
?>
<?php
$data = array();
if(mysqli_num_rows($result)>0){
while($row = mysqli_fetch_array($result)){
array_push($data, $row['status']);
}
}
echo json_encode($data);
?>
the code is executed and the status in database table is changed but I got error in console : SyntaxError: JSON.parse: unexpected character at line 4 column 2 of the JSON data
How can I solve this issue which I think I need to rewrite json_encode but I don't know how?
$.ajax({
type: 'post',
dataType: 'json',
cache: false,
url: 'setpp.php',
success: function (response) {
$.each(response, function(i, item) {
alert(item);
});
},
error: function () {
alert("error");
},
});
example php answer setpp.php
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
array_push($data, $row['status']);
}
die(json_encode($data));
} else {
$answer = array(
'No Records'
);
die(json_encode($answer));
}
I think the problem is the value returned by setpp.php.
remember to die(), otherwise the php answer will not be correct
Iam facnigg and issue with ajax, Im working on a contact form and I have an issue with the ajax call,
The call is never succseed, even if the field are all typed correctly.
I tried few things but nothing is working
Somene can give me an advice..?
Many thanks.
$.ajax({
url: "assets/contact_form/process-contact.php",
type: "POST",
dataType: "html",
data: userData,
beforeSend: function () {
$( sb ).html('Sending...');
},
success: function (response) {
if (response == true) {
setTimeout(function () {
window.location = 'index.html';
}, 1000);
} else {
$( sb ).html('Can not send, please try latter'); //IT GOES STRIGHT TO HERE
}
}
});
}
});
here is the php code:
<?php
$userData['name'] = filter_var(trim($_POST['name']),
FILTER_SANITIZE_STRING);
$userData['email'] = filter_var(trim($_POST['email']),
FILTER_VALIDATE_EMAIL);
$userData['phone'] = filter_var(trim($_POST['phone']),
FILTER_SANITIZE_STRING);
$userData['message'] = filter_var(trim($_POST['message']),
FILTER_SANITIZE_STRING);
if( ! in_array( null, $userData ) ){
$my_email = 'roni.itzhaik#gmail.com';
$nameRegx = "/^[' a-zא-ת]+(\s[' a-zא-ת]+)*$/i";
$phoneRegx = "/^(?:0(?!(5|7))(?:2|3|4|8|9))(?:-?\d){7}$|^(0(?=5|7)(?:-?\d)
{9})$/";
if( strlen($userData['name']) > 2 && strlen($userData['name']) < 70 &&
preg_match($nameRegx, $userData['name']) ) {
if( preg_match($phoneRegx, $userData['phone']) ){
if( strlen($userData['message']) > 2 ){
$subject = 'Message from ' . $userData['name'] ;
$message_phone= $userData['message'].'Phone number:
'.$userData['phone'];
$headers = 'From: ' . $userData['email']. "\r\n";
mail($my_email, $subject, $message_phone, $headers);
// send mail
// Save data to db (DON'T FORGET TO CLEAN AGAINST SQL INJECTIONS!!!)
echo true;
}}}}
This may work.
......
if (response) {
setTimeout(function () {
window.location = 'index.html';
.....
It will be better if you could return an object instead :
echo json_encode(['success' => true]);
Then the check in your success callback will looks like :
if (response.success){
//Your logic
}
Hope this helps.
I have read many answers on stack overflow but I can't find an apt answer. I want to send multiple variables from php file to a javascript file. I want to use those variables later separately. So please explain with a simple example of how to get the variables from php file and how to use them separately later.
This is my js.
<script>
function here(card_numb) {
alert("pk!");
$.ajax({
url: 'details.php',
type: "GET",
dataType: 'json',
data: ({
card_number: card_numb
}),
success: function(data) {
console.log('card_number:'+data.card_number+'book_issued:'+data.book_isued);
}
});
}
I'm getting the alert 'pk!'. But $.ajax ain't working.
This is details.php
<?php
if(isset($_GET['card_number'])){
$card_number = $_GET['card_number'];
$query = "Select * from users where card_number = '".$card_number."'";
$query_run = mysqli_query($link,$query);
$row_numb =#mysqli_num_rows($query_run);
if($row_numb == 0){
echo "<div class='bdiv1'>No such number found!</div>";
} else{
$row=mysqli_fetch_assoc($query_run);
$book1 = $row['user_name'];
$arr = array('isued_book' => $book1,'card_number' => $card_number);
echo json_encode($arr);
exit();
}
}
?>
Thank you!
somthing.js - ur jspage
<script>
function here(card_numb) {
$.ajax({
url: 'details.php',
type: 'GET',
dataType: 'json',
data: {
card_number: card_numb
},
success: function(data) {
console.log('card_number:'+data.card_number+'book_issued:'+data.isued_book);
}
});
}
success: function(result){
console.log('variable1:'+result.var1+'variable2:'+result.var2+'variable3:'+result.var3);
} });
details.php
<?php
if(isset($_GET['card_number'])){
$card_number = $_GET['card_number'];
$query = "Select * from users where card_number = ".$card_number;
$query_run = mysqli_query($link,$query);
$row_numb =#mysqli_num_rows($query_run);
if(!$query_run){
echo "<div class='bdiv1'>No such number found!</div>";
} else {
$row=mysqli_fetch_assoc($query_run);
$book1 = $row['user_name'];
$arr = array('isued_book' => $book1,'card_number' => $card_number);
echo json_encode($arr);
exit();
}
if the currect value get in $row you can get the result in console
I am doing an ajax call like this:
function myCall() {
var request = $.ajax({
url: "ajax.php",
type: "GET",
dataType: "html"
});
request.done(function(data) {
$("image").attr('src',data);
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
}
This is my ajax.php:
<?php
$connection = mysql_connect ("",
"", "");
mysql_select_db("");
// QUERY NEW ONE
$myquery = "SELECT * FROM mytable ORDER BY rand() LIMIT 1";
$result = mysql_query($myquery);
while($row = mysql_fetch_object($result))
{
$currentid = "$row->id";
$currentname = "$row->name";
$currenturl = "$row->url";
$currentimage = "$row->image";
echo $currenturl,$currentnam, $currenturl,$currentimage;
}
mysql_close($connection);
?>
My data variable from the ajax call now contains all variables at once:
($currenturl,$currentnam, $currenturl,$currentimage)
How can I separate them so I can do something like:
request.done(function(data) {
$("id").attr('src',data1);
$("name").attr('src',data2);
$("url").attr('src',data3);
$("image").attr('src',data4);
});
jQuery :
$.ajax({
type:"POST",
url:"ajax.php",
dataType:"json",
success:function(response){
var url = response['url'];
var name = response['name'];
var image = response['image'];
// Now do with the three variables
// $("id").attr('src',data1);
// $("name").attr('src',data2);
// $("url").attr('src',data3);
// $("image").attr('src',data4);
},
error:function(response){
alert("error occurred");
}
});
From your code:
echo $currenturl,$currentnam, $currenturl,$currentimage;
Replace the above line with the code below:
$array = array('url'=>$currenturl, 'name'=>$currentname, 'image'=>$currentimage);
echo json_encode($array);
instead of string return an array i.e. use json type for returning value
i.e instead of
echo $currenturl,$currentnam, $currenturl,$currentimage;
use
echo json_encode array('current' => $currenturl,'currentnam' => $currentnam, 'currenturl' => $currenturl,'currentimage' => $currentimage);
and also write 'dataType' as 'json' in ajax