I'm currently requesting some text via jQuery on a php page. The problem is that the new line symbols \n are displayed in the alert window, and do not get interpreted as new line. I do not escape the string at any time.
In the error: function(..) block of my jQuery request, I get the string returned by php via jqXHR.responseText, here is it's exact value :
Some fields are empty!\n$name= \n$schedule= 480;1140;480;1140;480;1140;480;1140;480;1140;480;1140;480;1140\n$free_connection= false\n$free_coffee= false\n$rating= -1\n$lat= 44.715513732021336\n$lng= 1.9775390625\n
When I do this, new lines DON'T WORK :
alert(jqXHR.responseText);
So to debug, I decided to paste the php response string (which is the previous string) directly in the alert() function, and in this case the new lines WORK :
alert("Some fields are empty!\n$name= \n$schedule= 480;1140;480;1140;480;1140;480;1140;480;1140;480;1140;480;1140\n$free_connection= false\n$free_coffee= false\n$rating= -1\n$lat= 44.715513732021336\n$lng= 1.9775390625\n)");
The string is exactly the same, but yet new lines don't work when I use jqXHR to get it.
Anybody has any clue ?
EDIT: php code that generates the string :
$errorMessage = 'Some fields are empty!' . '\n'
. '$name= ' . $name . '\n'
. '$schedule= ' . $schedule . '\n'
. '$free_connection= ' . $free_connection . '\n'
. '$free_coffee= ' . $free_coffee . '\n'
. '$rating= ' . $rating . '\n'
. '$lat= ' . $lat . '\n'
. '$lng= ' . $lng . '\n';
echo $errorMessage;
You're using the wrong type of quotes. In PHP, escape sequences aren't processed in single quotes, only in double quotes. So it should be:
$errorMessage = 'Some fields are empty!' . "\n"
. '$name= ' . $name . "\n"
. '$schedule= ' . $schedule . "\n"
. '$free_connection= ' . $free_connection . "\n"
. '$free_coffee= ' . $free_coffee . "\n"
. '$rating= ' . $rating . "\n"
. '$lat= ' . $lat . "\n"
. '$lng= ' . $lng . "\n";
echo $errorMessage;
I do not know if I understood well but You can try
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
or
$.getJSON( "ajax/test.json", function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});
Related
Trying to set up a WhatsApp button with a custom message, I've created a script in JavaScript to do that and calling it onclick.
I've tried moving quotation marks around but nothing works, this might be a silly issue but I just started with coding and can't get this to work, been trying since yesterday.
Here is my JavaScript code:
function sendSms(number, title) {
window.open('https://api.whatsapp.com/send?phone=' + number + '&text=' + 'hello' + title);
}
Here is my PHP code:
echo '<span class="ad-whatsapp" onclick="sendSms(\' '. $ad_wa .' , '. str_replace(" ", "%20", get_the_title()) . '\')"></span>';
It seems to be sending the whole content of the parenthesis as the number parameter instead of separating the 2.
function sendSms(number, title) {
window.open('https://api.whatsapp.com/send?phone=' + number + '&text=' + 'hello' + title);
}
echo '<span class="ad-whatsapp" onclick="sendSms(\' '. $ad_wa .'\' , \''. str_replace(" ", "%20", get_the_title()) . '\')">bb</span>';
Try using this JavaScript:
function sendSms(number, title) {
window.open(`https://api.whatsapp.com/send?phone=${number}&text=hello${title}`);
}
With this PHP:
<?php
$replaced = str_replace(" ", "%20", get_the_title());
echo '<span class="ad-whatsapp" onclick="sendSms(\'' . $ad_wa . '\', \'' . $replaced . '\')">SEND</span>';
?>
Good luck.
Try using this instead:
echo "<span class='ad-whatsapp' onclick=\"sendSms('".$ad_wa."' , '".str_replace(" ", "%20", $this->get_the_title())."')\">asdf</span>";
In php, I want to pass a php variable using the jquery.post method.
The first figure shows the code that post the variable
first
The second figure shows to read the posted variable.second
php variable contains some statements, but output will print the variable names like "$rxss", "$sxss".
The post method seems to be writing the data part incorrectly, so please let me know how to write it.
add
i already tested
echo '<script type="text/javascript">
$(document).ready(function() {
$.post("scanner/getStatus.php", {testId:' . "$testId" . ',chkCnt:' . "$chkCount" . ',rxss:' . "$rxss" . ',sxss:' . "$sxss" . ',sqli:' . "$sqli" . ',basqli:' . "$basqli" . ',autoc:' . "$autoc" . ',idor:' . "$idor" . ',dirlist:' . "$dirlist" . ',bannerdis:' . "$bannerdis" . ',sslcert:' . "$sslcert" . ',unredir:' . "$unredir" . ',clamav:' . "$clamav" . '}, function(data){$("#status").html(data)});
var refreshId = setInterval(function() {
$.post("scanner/getStatus.php", {testId:' . "$testId" . ',chkCnt:' . "$chkCount" . ',rxss:' . "$rxss" . ',sxss:' . "$sxss" . ',sqli:' . "$sqli" . ',basqli:' . "$basqli" . ',autoc:' . "$autoc" . ',idor:' . "$idor" . ',dirlist:' . "$dirlist" . ',bannerdis:' . "$bannerdis" . ',sslcert:' . "$sslcert" . ',unredir:' . "$unredir" . ',clamav:' . "$clamav" . '}, function(data){$("#status").html(data)});
}, 500); ......
-
echo '<script type="text/javascript">
$(document).ready(function() {
$.post("scanner/getStatus.php", {testId:' . "$testId" . ',chkCnt:' . "$chkCount" . ',rxss:"" + $rxss + "",sxss:"" + $sxss + "",sqli:""+ $sqli + "",basqli:"" + $basqli + "",autoc:"" + $autoc + "",idor:"" + $idor + "",dirlist:"" + $dirlist + "",bannerdis:"" + $bannerdis + "",sslcert:"" + $sslcert + "",unredir:"" + $unredir + "",clamav:"" + $clamav + ""}, function(data){$("#status").html(data)});
var refreshId = setInterval(function() {
$.post("scanner/getStatus.php", {testId:' . "$testId" . ',chkCnt:' . "$chkCount" . ',rxss:"" + $rxss + "",sxss:"" + $sxss + "",sqli:""+ $sqli + "",basqli:"" + $basqli + "",autoc:"" + $autoc + "",idor:"" + $idor + "",dirlist:"" + $dirlist + "",bannerdis:"" + $bannerdis + "",sslcert:"" + $sslcert + "",unredir:"" + $unredir + "",clamav:"" + $clamav + ""}, function(data){$("#status").html(data)});
}, 500); ......
but when these test not showing getStatus.php and apache log haven't error
You can you this $("$yourvariable")
Also take a look at this How to call PHP function from string stored in a Variable
I need to output some strings in the onclick anchor function.I have used proper escaping but anyhow its returning error.
My code is:
$output .= '<a title="Minus this" href="#" onclick = removefromCart("' . $item . '", "' . $nonce . '", ' . $deductQty . ');></a>';
And also used this :
$output .= '<a title="Minus this" href="#" onclick = "removefromCart("' . $item . '", "' . $nonce . '", ' . $deductQty . ')"></a>';
But in both cases there is Uncaught SyntaxError: Unexpected token }
The quotes is totally wrong. Do this way, using the first one:
$output .= '<a title="Minus this" href="#" onclick=\'removefromCart("' . $item . '", "' . $nonce . '", ' . $deductQty . ');\'></a>';
See the 's I have added and removed spaces? And please, next time, don't mingle both PHP and JavaScript. It's confusingly dangerous.
See also:
Are single quotes allowed in HTML?
Is there a better way to write this php code?
You should use single quotations to represent string in HTML element
$output .= '<a title="Minus this" href="#" onclick = "removefromCart(\'' . $item . '\', \'' . $nonce . '\', ' . $deductQty . ')"></a>';
For greater than or equal to PHP5
$output .= '<a title="Minus this" href="#" onclick = removefromCart($item,$nonce,$deductQty);></a>';
For Less than PHP5 try it
$output .= '<a title="Minus this" href="#" onclick = removefromCart(' . $item . ',' . $nonce . ', ' . $deductQty . ');></a>';
echo '<script>
function ' . $row['idname'] . 'Click(){
$( "#flip-' . $row['idname'] . '" ).flipswitch( "disable" );
var isOff = document.getElementById("flip-' . $row['idname'] . '").value;
if(isOff == "off"){
console.log("action.php?do=turn-off-' . $row["id"] . '");
jQuery.ajax({
url: "action.php?do=turn-off-' . $row["id"] . '",
type: "GET",
success:function (data) {
$( "#flip-' . $row['idname'] . '" ).flipswitch( "enable" );
console.log("SUCCESS!!");
}
});
}else{
console.log("action.php?do=turn-on-' . $row["id"] . '");
jQuery.ajax({
url: "action.php?do=turn-on-' . $row["id"] . ',
type: "GET",
success : function (data) {
$( "#flip-' . $row['idname'] . '" ).flipswitch( "enable" );
console.log("SUCCESS!!");
}
});
}
}
</script><br>';
So my problem is that ajax doesn't even load the page that is requested.
It creates this code from the result of a MySQL query, so it's basically a JavaScript file in a PHP File. The target is an empty page that only has some functions.
The function is invoked onChange from this <select>:
echo '<div class="ui-field-contain" style="width: 100%;">
<label for="flip-' . $row['idname'] . '">' . $row['name'] . '</label>
<select onchange="' . $row['idname'] . 'Click()" name="flip-' . $row['idname'] . '" id="flip-' . $row['idname'] . '" data-role="flipswitch">
<option value="off" selected="">Aus</option> <option value="on">An</option>
</select>
</div>';
This may solve the problem because it is not a nice way to just replace it with always. You might consider adding some error handling where no wrong elements are tested to be selected with the error message as a part of the id.
Deprecated jqXHR.success()
The issue may occur because this method is deprecated since jQuery 1.8. It has been replaced by jqXHR.done().
jQuery.ajax({
url: "action.php?do=turn-on-' . $row["id"] . '",
type: "GET",
done: function (data) {
$( "#flip-' . $row['idname'] . '" ).flipswitch( "enable" );
console.log("SUCCESS!!");
}
});
Suggesting another way
$.get("api.php", {
do: "turn-on-' . $row["id"] . '"
}, function (data) {
console.log(data);}
});
I have the following code which parses the Twitter text to change links, mentions and hashes into hyperlinks:
function parseTwitterText($text) {
$returnText = $text;
$hashPattern = '/\#([A-Za-z0-9\_]+)/i';
$mentionPattern = '/\#([A-Za-z0-9\_]+)/i';
$urlPattern = '/(http[s]?\:\/\/[^\s]+)/i';
$robotsFollow = false;
// SCAN FOR LINKS FIRST!!! Otherwise it will replace the hashes and mentions
$returnText = preg_replace($urlPattern, '\<a href\="$1" ' + (($robotsFollow)? '':'rel\=\"nofollow\"') + '\>$1\<\/a\>', $returnText);
$returnText = preg_replace($hashPattern, '\<a href\="http\:\/\/twitter\.com\/\#\!\/search\?q\=\%23$1" ' + (($robotsFollow)? '':'rel\=\"nofollow\"') + '\>\#$1\<\/a\>', $returnText);
$returnText = preg_replace($mentionPattern, '\<a href\="http\:\/\/twitter\.com\/$1" ' + (($robotsFollow)? '':'rel\=\"nofollow\"') + '\>#$1\<\/a\>', $returnText);
return $returnText;
}
However I'm just getting 0 returned if I had a tweet like #test
I based this code on a JavaScript version I had, so wondering if I've done something wrong in the preg_replace() that only worked in the JS replace()
There are 2 problems in your code:
In PHP, you concatenate strings with ., not with a +. When using +, PHP is casting the strings to an integer before adding them, which results in the 0.
In the preg_replace() calls, you do not have to escape all the characters in the second parameter. So remove all backslashes within these three lines.
You should end up with something like this:
$returnText = preg_replace($urlPattern, '<a href="$1" ' . (($robotsFollow)? '':'rel="nofollow"') . '>$1</a>', $returnText);
$returnText = preg_replace($hashPattern, '<a href="http://twitter.com/#!/search?q=%23$1" ' . (($robotsFollow)? '':'rel="nofollow"') . '>#$1</a>', $returnText);
$returnText = preg_replace($mentionPattern, '<a href="http://twitter.com/$1" ' . (($robotsFollow)? '':'rel="nofollow"') . '>#$1</a>', $returnText);
In PHP, you use . to concatenate two strings, not + as you would in JavaScript. Also, as BluePsyduck mentioned, you don't have to escape all the characters as you're currently doing.
Change the preg_replace() statements as follows:
$returnText = preg_replace($urlPattern,
'<a href="$1" ' .
(($robotsFollow)? '' : 'rel="nofollow"') .
'>$1</a>', $returnText);
$returnText = preg_replace($hashPattern,
'<a href="http://twitter.com/#!/search?q=%23$1" ' .
(($robotsFollow)? '' : 'rel="nofollow"') .
'>#$1</a>', $returnText);
$returnText = preg_replace($mentionPattern,
'<a href="http://twitter.com/$1" ' .
(($robotsFollow)? '' : 'rel="nofollow"') .
'>#$1</a>', $returnText);
Test:
header('Content-Type: text/plain');
echo parseTwitterText('#foo lala');
echo parseTwitterText('#test');
Output:
#foo lala
#test
Demo.